Thursday, April 28, 2005

Back to C++

To initialize an object, you can't do like Java:

Employee x = new Employee();

To do this in C++, you just use:

Employee x;

And to define a class, you don't say public like you do in java:

public class Employee { ... } // not working in C/C++;

class Employee( ... ) // working in C++.


-----------------------------------------------
Variable Scope
File scope variables by default have external linkage meaning they are visible across all the files in your project.

The keyword static now prefaces the declaration of a in file1.cpp, limiting its visibility to file1.cpp

#include
using namespace std;
static int a = 1;
void someFunction();
void someFunction(){
cout<<a<<endl;
}

-------------------------------------------------
How to delete an array of pointers?

int *int_pointers[3] = {NULL};
for(int i = 0; i<3; i++)
delete int_pointers[i];

I don't know if there is some other way.

-------------------------------------------------
Pointer to a pointer is a pointer to an array, right?

int** int_pointer_array;
for(int i = 0; i<3; i++)
int_pointer_array[i] = new int(i+1);
for(int i = 0; i<3; i++)
cout<<*int_pointer_array[i]<<endl;
for(int i = 0; i<3; i++)
delete int_pointer_array[i]; //release memory for each object
delete[] int_pointer_array; //then release the array

Another way:

int array_size = 0;
int* int_array = NULL;
cout<<"Please enter array size: ";
cin>>array_size;
int_array = new int[array_size];
for(int i=0; i<array_size; i++)
int_array[i] = i+1;
for(int i=0; i<array_size; i++)
cout<<int_array[i]<<endl;
delete[] int_array; //release the array when done

----------------------------------------------------
Static Function Variables

The local function variables are created and destroyed with each invocation of their associated function. If you want a local variable to retain its value between function calls you must declare the variable as being static using the static keyword.
A static local function variable will be initialized when the function is first called. Any change to the value of a static variable will be preserved for use by the next invocation of the function.

#include "testfunctiontwo.h"
#include
using namespace std;

void testFunctionTwo(){
static int i = 0;
int j = 0;
cout<<"Local Static i = "<<i++<<endl;
cout<<"Local Auto j = "<<j++<<endl;
}

---------------------------------------------------------------
Local variable and global variable:

int i = 25;
void testFunction(int i){
cout << "Local i " << i << endl;
cout << "Global i " << ::i << enl;
}
Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?