Monday, June 29, 2009

An example of formatted output



NOTE : -
THIS CONTENT IS NOT ORIGINAL

33. An example of formatted output

This program performs formatted output two different ways. Please note the
width() and setw() MODIFIERS are only effective on the next item output to the stream. Subsequent items will not be influenced.


using namespace std;
#include
#include

int main ()
{
int i;

cout << "A list of numbers:" << endl;
for (i = 1; i <= 1024; i *= 2)
{
cout.width (7);
cout << i << endl;
}

cout << "A table of numbers:" << endl;
for (i = 0; i <= 4; i++)
{
cout << setw(3) << i << setw(5) << i * i * i << endl;
}

return 0;
}


Output
A list of numbers:
1
2
4
8
16
32
64
128
256
512
1024
A table of numbers:
0 0
1 1
2 8
3 27
4 64



You now have a basic knowledge about C++. Inside good books you will learn many more things. The file management system is very powerful, it has many other possibilities than those illustrated here. There is also a lot more to say about classes: template classes, virtual classes...

In order to work efficiently with C++ you will need a good reference book, just like you need one for C. You will also need information on how C++ is used in your particular domain of activity. The standards, the global approach, the tricks, the typical problems encountered and their solutions... The best reference is of course the books written by Bjarne Stroustrup himself (I don't recall which of them I read). The following book contains almost every detail about C and C++ and is constructed in a way similar to this text

BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

Character arrays can be used like files



NOTE : -
THIS CONTENT IS NOT ORIGINAL

32. Character arrays can be used like files

Generally speaking, it is possible to do on character arrays the same operations as on files. This is very useful to convert data or manage memory arrays.

Here is a program that writes inside a character array:


using namespace std;
#include
#include
#include
#include

int main ()
{
char a[1024];
ostrstream b(a, 1024);

b.seekp(0); // Start from first char.
b << "2 + 2 = " << 2 + 2 << ends; // ( ends, not endl )
// ends is simply the
// null character '\0'
cout << a << endl;

double v = 2;

strcpy (a, "A sinus: ");

b.seekp(strlen (a));
b << "sin (" << v << ") = " << sin(v) << ends;

cout << a << endl;

return 0;
}


Output
2 + 2 = 4
A sinus: sin (2) = 0.909297



A program that reads from a character string:


using namespace std;
#include
#include
#include

int main ()
{
char a[1024];
istrstream b(a, 1024);

strcpy (a, "45.656");

double k, p;

b.seekg(0); // Start from first character.
b >> k;

k = k + 1;

cout << k << endl;

strcpy (a, "444.23 56.89");

b.seekg(0);
b >> k >> p;

cout << k << ", " << p + 1 << endl;

return 0;
}


Output
46.656
444.23, 57.89




BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

Brief examples of file I/O



NOTE : -
THIS CONTENT IS NOT ORIGINAL

31. Brief examples of file I/O

Let's talk about input/output. In C++ that's a very broad subject.

Here is a program that writes to a file:


using namespace std;
#include
#include

int main ()
{
fstream f;

f.open("test.txt", ios::out);

f << "This is a text output to a file." << endl;

double a = 345;

f << "A number: " << a << endl;

f.close();

return 0;
}


Content of file test.txt
This is a text output to a file.
A number: 345



Here is a program that reads from a file:



using namespace std;
#include
#include

int main ()
{
fstream f;
char c;

cout << "What's inside the test.txt file" << endl;
cout << endl;

f.open("test.txt", ios::in);

while (! f.eof() )
{
f.get(c); // Or c = f.get()
cout << c;
}

f.close();

return 0;
}


Output
This is a text output to a file.
A number: 345



BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

ENCAPSULATION: public, protected and private



NOTE : -
THIS CONTENT IS NOT ORIGINAL

30. ENCAPSULATION: public, protected and private

The public: directive means the variables or the methods below can be accessed and used everywhere in the program.

If you want the variables and methods to be accessible only to methods of the class AND to methods of derived classes, then you must put the keyword
protected:before them.

If you want variables or methods to be accessible ONLY to methods of the class, then you must put the keyword
private: before them.

The fact that variables or methods are declared private or protected means that nothing external to the class can access or use them. That's ENCAPSULATION. (If you want to give a specific function the right to access those variables and methods, then you must include that function's prototype inside the class definition, preceded by the keyword
friend.)

Good practice is to encapsulate all the variables of a class. This can sound strange if you're used to structs in C. Indeed a struct only makes sense if you can access its data... In C++ you have to create methods to acces the data inside a class. The example below uses the basic example of chapter 17, yet declares the class data to be protected:


using namespace std;
#include

class vector
{
protected:

double x;
double y;

public:

void set_x (int n)
{
x = n;
}
   void set_y (int n)
{
y = n;
}
double surface ()
{
double s;
s = x * y;
if (s < 0) s = -s;
return s;
}
};

int main ()
{
vector a;

a.set_x (3);
a.set_y (4);

cout << "The surface of a: " << a.surface() << endl;

return 0;
}


Output
The surface of a: 12



The example above is a bit odd since the class data x and y can be set but they cannot be read back. Any attempt in function main () to read
a.x or a.y will result in a compilation error. In the next example, x and y can be read back:


using namespace std;
#include

class vector
{
protected:

double x;
double y;

public:

void set_x (int n)
{
x = n;
}
   void set_y (int n)
{
y = n;
}

double get_x ()
{
return x;
}
   double get_y ()
{
return y;
}
double surface ()
{
double s;
s = x * y;
if (s < 0) s = -s;
return s;
}
};

int main ()
{
vector a;

a.set_x (3);
a.set_y (4);

cout << "The surface of a: " << a.surface() << endl;
cout << "The width of a: " << a.get_x() << endl;
cout << "The height of a: " << a.get_y() << endl;

return 0;
}


Output
The surface of a: 12
The width of a: 3
The height of a: 4



In C++ one is not supposed to access the data of a class directly. Methods have to be declared. Why is this? Many reasons exist. One is that this allows you to change the way the data is represented within the class. Another reason is this allows data inside the class to be cross-dependent. Suppose
x and y must always be of the same sign, otherwise ugly things can happen... If one is allowed to access the class data directly, it would be easy to impose say a positive x and a negative y. In the example below, this is strictly controlled:


using namespace std;
#include

int sign (double n)
{
if (n >= 0) return 1;
return -1;
}

class vector
{
protected:

double x;
double y;

public:

void set_x (int n)
{
x = n;
if (sign (x) != sign(y)) y = -y;
}
   void set_y (int n)
{
y = n;
if (sign (y) != sign(x)) x = -x;
}

double get_x ()
{
return x;
}
   double get_y ()
{
return y;
}
double surface ()
{
double s;
s = x * y;
if (s < 0) s = -s;
return s;
}
};

int main ()
{
vector a;

a.set_x (-3);
a.set_y (4);

cout << "The surface of a: " << a.surface() << endl;
cout << "The width of a: " << a.get_x() << endl;
cout << "The height of a: " << a.get_y() << endl;

return 0;
}


Output
The surface of a: 12
The width of a: 3
The height of a: 4




BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

Class derivation allows you to write generic methods



NOTE : -
THIS CONTENT IS NOT ORIGINAL

29. Class derivation allows you to write generic methods

Class derivation allows you to construct more complex classes built from base classes. There is another application of class derivation: allowing the programmer to write generic functions.

Suppose you define a base class with no variables. It makes no sense to use instances of that class inside your program. But then you write a function whose purpose it is to sort instances of that class. That function will be able to sort any type of object provided it belongs to a class derived from that base class! The only condition is that inside of each derived class definition, all methods that the sort function needs are correctly defined:


using namespace std;
#include
#include

class octopus
{
public:

virtual double module() = 0; // = 0 implies function is not
// defined. This makes instances
// of this class cannot be declared.
};

double biggest_module (octopus &a, octopus &b, octopus &c)
{
double r = a.module();
if (b.module() > r) r = b.module();
if (c.module() > r) r = c.module();
return r;
}

class vector: public octopus
{
public:

double x;
double y;

vector (double a = 0, double b = 0)
{
x = a;
y = b;
}

double module()
{
return sqrt (x * x + y * y);
}
};

class number: public octopus
{
public:

double n;

number (double a = 0)
{
n = a;
}

double module()
{
if (n >= 0) return n;
else return -n;
}
};

int main ()
{
vector k (1,2), m (6,7), n (100, 0);
number p (5), q (-3), r (-150);

cout << biggest_module (k, m, n) << endl;
cout << biggest_module (p, q, r) << endl;

cout << biggest_module (p, q, n) << endl;

return 0;
}


Output
100
150
100



Perhaps you think "okay, that's a good idea to derive classes from the class octopus because that way I can apply it to instances of my class's methods and function that were designed in a generic way for the octopus class. But what if there's another base class, named cuttlefish, which has very interesting methods and functions too? Do I have to make my choice between octopus and cuttlefish when I want to derive a class?" No, of course not. A derived class can be derived from bothoctopus and cuttlefish. That's POLYMORPHISM. The derived class simply has to define the methods necessary for octopus together with the methods necessary for cuttlefish:


class octopus
{
virtual double module() = 0;
};

class cuttlefish
{
virtual int test() = 0;
};

class vector: public octopus, public cuttlefish
{
double x;
double y;

double module ()
{
return sqrt (x * x + y * y);
}

int test ()
{
if (x > y) return 1;
else return 0;
}
}





BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

A class can be derived from more than one base class



NOTE : -
THIS CONTENT IS NOT ORIGINAL

28. A class can be derived from more than one base class

Maybe you wonder if a class can be derived from more than one base class. The answer is yes:


using namespace std;
#include
#include

class vector
{
public:

double x;
double y;

vector (double a = 0, double b = 0)
{
x = a;
y = b;
}

double surface()
{
return fabs (x * y);
}
};

class number
{
public:

double z;

number (double a)
{
z = a;
}

int is_negative ()
{
if (z < 0) return 1;
else return 0;
}
};

class trivector: public vector, public number
{
public:

trivector(double a=0, double b=0, double c=0): vector(a,b), number(c)
{
} // The trivector constructor calls the vector
// constructor, then the number constructor,
// and in this example does nothing more.

double volume()
{
return fabs (x * y * z);
}
};

int main ()
{
trivector a(2, 3, -4);

cout << a.volume() << endl;
cout << a.surface() << endl;
cout << a.is_negative() << endl;

return 0;
}


Output
24
6
1




BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

If a method is declared virtual the program will always check the type of the instance that is pointed to and will use the appropriate method



NOTE : -
THIS CONTENT IS NOT ORIGINAL

27. If a method is declared virtual the program will always check the type of the instance that is pointed to and will use the appropriate method

In the program above,
r->module() calculates the vector module, using x and y, because r has been declared a vector pointer. The fact that r actually points to a trivector is not taken into account. If you want the program to check the type of the pointed object and choose the appropriate method, then you must declare that method as virtual inside the base class.

(If at least one of the methods of the base class is virtual then a "header" of 4 bytes is added to every instance of the classes. This allows the program to determine what a vector actually points to.) (4 bytes is probably implementation specific. On a 64 bit machine maybe it is 8 bytes...)


using namespace std;
#include
#include

class vector
{
public:

double x;
double y;

vector (double a = 0, double b = 0)
{
x = a;
y = b;
}

virtual double module()
{
return sqrt (x*x + y*y);
}
};

class trivector: public vector
{
public:
double z;

trivector (double m = 0, double n = 0, double p = 0)
{
x = m; // Just for the game,
y = n; // here I do not call the vector
z = p; // constructor and I make the
} // trivector constructor do the
// whole job. Same result.

double module ()
{
return sqrt (x*x + y*y + z*z);
}
};

void test (vector &k)
{
cout << "Test result: " << k.module() << endl;
}

int main ()
{
vector a (4, 5);
trivector b (1, 2, 3);

cout << "a (4, 5) b (1, 2, 3)" << endl << endl;

vector *r;

r = &a;
cout << "module of vector a: " <<>module() << endl;

r = &b;
cout << "module of trivector b: " <<>module() << endl;

test (a);

test (b);

vector &s = b;

cout << "module of trivector b: " << s.module() << endl;

return 0;
}


Output
a (4, 5) b (1, 2, 3)

module of vector a: 6.40312
module of trivector b: 3.74166
Test result: 6.40312
Test result: 3.74166
module of trivector b: 3.74166




BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

A class can be DERIVED from another class



NOTE : -
THIS CONTENT IS NOT ORIGINAL

26. A class can be DERIVED from another class

A class can be DERIVED from another class. The new class INHERITS the variables and methods of the BASE CLASS. Additional variables and/or methods can be added:


using namespace std;
#include
#include

class vector
{
public:

double x;
double y;

vector (double a = 0, double b = 0)
{
x = a;
y = b;
}

double module()
{
return sqrt (x*x + y*y);
}

double surface()
{
return x * y;
}
};

class trivector: public vector // trivector is derived from vector
{
public:
double z; // added to x and y from vector

trivector (double m=0, double n=0, double p=0): vector (m, n)
{
z = p; // Vector constructor will
} // be called before trivector
// constructor, with parameters
// m and n.

trivector (vector a) // What to do if a vector is
{ // cast to a trivector
x = a.x;
y = a.y;
z = 0;
}

double module () // define module() for trivector
{
return sqrt (x*x + y*y + z*z);
}

double volume ()
{
return this->surface() * z; // or x * y * z
}
};

int main ()
{
vector a (4, 5);
trivector b (1, 2, 3);

cout << "a (4, 5) b (1, 2, 3) *r = b" << endl << endl;

cout << "Surface of a: " << a.surface() << endl;
cout << "Volume of b: " << b.volume() << endl;
cout << "Surface of base of b: " << b.surface() << endl;

cout << "Module of a: " << a.module() << endl;
cout << "Module of b: " << b.module() << endl;
cout << "Module of base of b: " << b.vector::module() << endl;

trivector k;
k = a; // thanks to trivector(vector) definition
// copy of x and y, k.z = 0
vector j;
j = b; // copy of x and y. b.z leaved out

vector *r;
r = &b;

cout << "Surface of r: " <<>surface() << endl;
cout << "Module of r: " <<>module() << endl;

return 0;
}


Output
a (4, 5) b (1, 2, 3) *r = b

Surface of a: 20
Volume of b: 6
Surface of base of b: 2
Module of a: 6.40312
Module of b: 3.74166
Module of base of b: 2.23607
Surface of r: 2
Module of r: 2.23607




BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

Sunday, June 28, 2009

Const variables inside a class definition



NOTE : -
THIS CONTENT IS NOT ORIGINAL

25. Const variables inside a class definition

A class variable can also be constant. That's just like static, except it is given a value inside the class declaration and that value cannot be modified:


using namespace std;
#include

class vector
{
public:

double x;
double y;
const static double pi = 3.1415927;

vector (double a = 0, double b = 0)
{
x = a;
y = b;
}

double cilinder_volume ()
{
return x * x / 4 * pi * y;
}
};

int main()
{
cout << "The value of pi: " << vector::pi << endl << endl;

vector k (3, 4);

cout << "Result: " << k.cilinder_volume() << endl;

return 0;
}


Output
The value of pi: 3.14159

Result: 28.2743





BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

Static variables inside a class definition



NOTE : -
THIS CONTENT IS NOT ORIGINAL

24. Static variables inside a class definition

One or more variables in a classcan be declared static. In which case, only one instance of those variables exist, shared by all instances of the class. It must be initialised outside the class declaration :


using namespace std;
#include

class vector
{
public:

double x;
double y;
static int count;

vector (double a = 0, double b = 0)
{
x = a;
y = b;
count++;
}

~vector()
{
count--;
}
};

int vector::count = 0;

int main ()
{
cout << "Number of vectors:" << endl;

vector a;
cout << vector::count << endl;

vector b;
cout << vector::count << endl;

vector *r, *u;

r = new vector;
cout << vector::count << endl;

u = new vector;
cout << a.count << endl;

delete r;
cout << vector::count << endl;

delete u;
cout << b.count << endl;

return 0;
}


Output
1
2
3
4
3
2





BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

An example of a complete class declaration



NOTE : -
THIS CONTENT IS NOT ORIGINAL

23. An example of a complete class declaration

Here is an example of a full class declaration:


using namespace std;
#include
#include

class vector
{
public:

double x;
double y;

vector (double = 0, double = 0);

vector operator + (vector);
vector operator - (vector);
vector operator - ();
vector operator * (double a);
double module();
void set_length (double = 1);
};

vector::vector (double a, double b)
{
x = a;
y = b;
}

vector vector::operator + (vector a)
{
return vector (x + a.x, y + a.y);
}

vector vector::operator - (vector a)
{
return vector (x - a.x, y - a.y);
}

vector vector::operator - ()
{
return vector (-x, -y);
}

vector vector::operator * (double a)
{
return vector (x * a, y * a);
}

double vector::module()
{
return sqrt (x * x + y * y);
}

void vector::set_length (double a)
{
double length = this->module();

x = x / length * a;
y = y / length * a;
}

ostream& operator << (ostream& o, vector a)
{
o << "(" << a.x << ", " << a.y << ")";
return o;
}

int main ()
{
vector a;
vector b;
vector c (3, 5);

a = c * 3;
a = b + c;
c = b - c + a + (b - a) * 7;
c = -c;

cout << "The module of vector c: " << c.module() << endl;

cout << "The content of vector a: " << a << endl;
cout << "The oposite of vector a: " << -a << endl;

c.set_length(2); // Transforms c in a vector of size 2.

a = vector (56, -3);
b = vector (7, c.y);

b.set_length(); // Transforms b in an unitary vector.

cout << "The content of vector b: " << b << endl;

double k;
k = vector(1, 1).module(); // k will contain 1.4142.
cout << "k contains: " << k << endl;

return 0;
}


Output
The module of vector c: 40.8167
The content of vector a: (3, 5)
The oposite of vector a: (-3, -5)
The content of vector b: (0.971275, 0.23796)
k contains: 1.41421



It is also possible to define a function to produces the sum of two vectors without mentioning it inside the vector class definition. Then it will not be a method of the class vector, but rather just a function that uses vectors:


vector operator + (vector a, vector b)
{
return vector (a.x + b.x, a.y + b.y);
}



In the example of a full class definition, above, the multiplication of a vector by a double is defined. Suppose we want the multiplication of a double by a vector to be defined too. Then we must write an isolated function outside the class:


vector operator * (double a, vector b)
{
return vector (a * b.x, a * b.y);
}



Of course the keywords new and delete work for class instances too. What's more, new automatically calls the constructor in order to initialize the objects, anddelete automatically calls the destructor before deallocating the memory the instance variables take:


using namespace std;
#include
#include

class vector
{
public:

double x;
double y;

vector (double = 0, double = 0);

vector operator + (vector);
vector operator - (vector);
vector operator - ();
vector operator * (double);
double module();
void set_length (double = 1);
};

vector::vector (double a, double b)
{
x = a;
y = b;
}

vector vector::operator + (vector a)
{
return vector (x + a.x, y + a.y);
}

vector vector::operator - (vector a)
{
return vector (x - a.x, y - a.y);
}

vector vector::operator - ()
{
return vector (-x, -y);

}

vector vector::operator * (double a)
{
return vector (a * x, a * y);
}

double vector::module()
{
return sqrt (x * x + y * y);
}

void vector::set_length (double a)
{
vector &the_vector = *this;

double length = the_vector.module();

x = x / length * a;
y = y / length * a;
}

ostream& operator << (ostream& o, vector a)
{
o << "(" << a.x << ", " << a.y << ")";
return o;
}

int main ()
{
vector c (3, 5);

vector *r; // r is a pointer to a vector.

r = new vector; // new allocates the memory necessary
cout << *r << endl; // to hold a vectors' variable,
// calls the constructor who will
// initialize it to 0, 0. Then finally
// new returns the address of the vector.

r->x = 94;
r->y = 345;
cout << *r << endl;

*r = vector (94, 343);
cout << *r << endl;

*r = *r - c;
r->set_length(3);
cout << *r << endl;

*r = (-c * 3 + -*r * 4) * 5;
cout << *r << endl;

delete r; // Calls the vector destructor then
// frees the memory.

r = &c; // r points towards vector c
cout << *r << endl;

r = new vector (78, 345); // Creates a new vector.
cout << *r << endl; // The constructor will initialise
// the vector's x and y at 78 and 345

cout << "x component of r: " <<>x << endl;
cout << "x component of r: " << (*r).x << endl;

delete r;

r = new vector[4]; // creates an array of 4 vectors

r[3] = vector (4, 5);
cout << r[3].module() << endl;

delete [] r; // deletes the array

int n = 5;
r = new vector[n]; // Cute!

r[1] = vector (432, 3);
cout << r[1] << endl;

delete [] r;

return 0;
}


Output
(0, 0)
(94, 345)
(94, 343)
(0.77992, 2.89685)
(-60.5984, -132.937)
(3, 5)
(78, 345)
x component of r: 78
x component of r: 78
6.40312
(432, 3)




BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

Arrays of instances can be declared



NOTE : -
THIS CONTENT IS NOT ORIGINAL

22. Arrays of instances can be declared

Of course, it is possible to declare arrays of objects:


using namespace std;
#include
#include

class vector
{
public:

double x;
double y;

vector (double a = 0, double b = 0)
{
x = a;
y = b;
}

double module ()
{
return sqrt (x * x + y * y);
}
};

int main ()
{
vector s [1000];

vector t[3] = {vector(4, 5), vector(5, 5), vector(2, 4)};

s[23] = t[2];

cout << t[0].module() << endl;

return 0;
}


Output
6.40312



BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

Saturday, June 27, 2009

The keyword this is a pointer to the instance a method is acting upon



NOTE : -
THIS CONTENT IS NOT ORIGINAL

21. The keyword this is a pointer to the instance a method is acting upon

When a method is applied to an instance, that method may use the instance's variables, modify them... But sometimes it is necessary to know the address of the instance. No problem, the keyword
this is intended for that purpose:


using namespace std;
#include
#include

class vector
{
public:

double x;
double y;

vector (double a = 0, double b = 0)
{
x = a;
y = b;
}

double module()
{
return sqrt (x * x + y * y);
}

void set_length (double a = 1)
{
double length;

length = this->module();

x = x / length * a;
y = y / length * a;
}
};

int main ()
{
vector c (3, 5);

cout << "The module of vector c: " << c.module() << endl;

c.set_length(2); // Transforms c in a vector of size 2.

cout << "The module of vector c: " << c.module() << endl;

c.set_length(); // Transforms b in an unitary vector.

cout << "The module of vector c: " << c.module() << endl;

return 0;
}


Output
The module of vector c: 5.83095
The module of vector c: 2
The module of vector c: 1





BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

The method bodies can be defined below the class definition (and Makefile usage example)



NOTE : -
THIS CONTENT IS NOT ORIGINAL

20. The method bodies can be defined below the class definition (and Makefile usage example)

If a method cannot be inline, or you do not want it to be inline, or if you want the class definition to contain the minimum amount of information (or you simply want the usual separate .h header file and .cpp source code file), then you need only put the prototype of the method inside the class and define the method below the class (or in a separate .cpp source file):


using namespace std;
#include

class vector
{
public:

double x;
double y;

double surface(); // The ; and no {} show it is a prototype
};

double vector::surface()
{
double s = 0;

for (double i = 0; i < x; i++)
{
s = s + y;
}

return s;
}

int main ()
{
vector k;

k.x = 4;
k.y = 5;

cout << "Surface: " << k.surface() << endl;

return 0;
}


Output
Surface: 20



For beginners:

If you intend to develop a serious C or C++ program, you need to separate the source code into
.h header files and .cpp source files. This is a short example of how it is done. The program above is split into three files :

A header file
vector.h:


class vector
{
public:

double x;
double y;

double surface();
};



A source file
vector.cpp:


using namespace std;
#include "vector.h"

double vector::surface()
{
double s = 0;

for (double i = 0; i < x; i++)
{
s = s + y;
}

return s;
}



And another source file
main.cpp:


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

int main ()
{
vector k;

k.x = 4;
k.y = 5;

cout << "Surface: " << k.surface() << endl;

return 0;
}


Assuming
vector.cpp is perfect, you compile it once and for all into a .o "object file". The command below produces that object code file, called vector.o:

g++ -c vector.cpp

Each time you modify the
main.cpp source file, you compile it into an executable file, say test20. You tell the compiler explicitly that it has to link the vector.oobject file into the final test20 executable:

g++ main.cpp vector.o -o test20

Run the executable this way:

./test20

This has several advantages:
  • The source code of vector.cpp need be compiled only once. This saves a lot of time on big projects. (Linking the vector.o file into the test20 executable is very fast.)
  • You can give somebody the .h file and the .o file(s). That way they can use your software but not change it because they don't have the .cpp file(s) (don't rely too much on this, wait until you master these questions).
Note you can compile main.cpp too into an object file and then link it with vector.o:

g++ -c main.cpp

g++ main.o vector.o test20

This wanders away from the "differences between C and C++" topic but if you want to look like a real programmer, you need to condense the above commands into a
Makefile and compile using the make command. The file content beneath is an oversimplified version of such a Makefile. Copy it to a file named Makefile. Please note, and this is very important, that the space before the g++ commands is mandatory and that it is a Tab character. Do not type the spacebar here. Instead use the tabulation key (full left of your keyboard, above the caps lock).


test20: main.o vector.o
g++ main.o vector.o -o test20

main.o: main.cpp vector.h
g++ -c main.cpp

vector.o: vector.cpp vector.h
g++ -c vector.cpp


In order to use that Makefile to compile, type:

make test20

The make command will parse through the file
Makefile and figure out what it has to do. To start with, it's told that test20 depends on main.o and vector.o. So it will automatically launch "make main.o" and "make vector.o". Then it will check if test20 already exists and checks the date stamps of test20, main.o andvector.o. If test20 already exists and main.o and vector.o have a date stamp earlier than test20, the make command determines that the current version oftest20 is up to date, so it has nothing to do. It will just report it did nothing. Otherwise, if test20 does not exist, or main.o or vector.o are more recent thantest20, the command that creates an up-to-date version of test20 is executed: g++ main.o vector.o -o test20.

This next version of the
Makefile is closer to a standard Makefile:


all: test20

test20: main.o vector.o
g++ main.o vector.o -o test20

main.o: main.cpp vector.h
g++ -c main.cpp

vector.o: vector.cpp vector.h
g++ -c vector.cpp

clean:
rm -f *.o test20 *~ #*


You trigger the compilation by just typing the
make command. The first line in the Makefile implies that if you just type make you intended "make test20":

make

This command erases all the files produced during compilation and all text editor backup files:

make clean




BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

Complex classes need the COPY CONSTRUCTOR and an overload of the = operator



NOTE : -
THIS CONTENT IS NOT ORIGINAL

19. Complex classes need the COPY CONSTRUCTOR and an overload of the = operator

If you cast an object like a vector, everything will happen correctly. For example, if vector k contains (4, 7), after the cast m = k the vector m will contain (4, 7) too. The values of k.x and k.y have simply been copied to m.x and m.y. Now suppose you're playing with objects like the person class above. Those objects contain a pointer to a character string. If you cast the person object by writing p = r it is necesary that some function does the work to make p be a correct copy of r. Otherwise, p.name will point to the same physical character string as r.name. What's more, the former character string pointed to by p.name is lost and becomes a memory zombie. The result will be catastrophic: a mess of pointers and lost data. The methods that will do the job are the COPY CONSTRUCTOR and an overload of the = operator:


using namespace std;
#include
#include

class person
{
public:

char *name;
int age;

person (char *n = "no name", int a = 0)
{
name = new char[100];
strcpy (name, n);
age = a;
}

person (const person &s) // The COPY CONSTRUCTOR
{
name = new char[100];
strcpy (name, s.name);
age = s.age;
}

person& operator= (const person &s) // overload of =
{
strcpy (name, s.name);
age = s.age;
return *this;
}

~person ()
{
delete [] name;
}
};

void modify_person (person& h)
{
h.age += 7;
}

person compute_person (person h)
{
h.age += 7;
return h;
}


int main ()
{
person p;
cout << p.name << ", age " << p.age << endl << endl;
// output: no name, age 0

person k ("John", 56);
cout << k.name << ", age " << k.age << endl << endl;
// output: John, age 56

p = k;
cout << p.name << ", age " << p.age << endl << endl;
// output: John, age 56

p = person ("Bob", 10);
cout << p.name << ", age " << p.age << endl << endl;
// output: Bob, age 10

// Neither the copy constructor nor the overload
// of = are needed for this operation that modifies
// p since just the reference towards p is passed to
// the function modify_person:
modify_person (p);
cout << p.name << ", age " << p.age << endl << endl;
// output: Bob, age 17

// The copy constructor is called to pass a complete
// copy of p to the function compute_person. The
// function uses that copy to make its computations
// then a copy of that modified copy is made to
// return the result. Finaly the overload of = is
// called to paste that second copy inside k:
k = compute_person (p);
cout << p.name << ", age " << p.age << endl << endl;
// output: Bob, age 17
cout << k.name << ", age " << k.age << endl << endl;
// output: Bob, age 24

return 0;
}


Output
no name, age 0

John, age 56

John, age 56

Bob, age 10

Bob, age 17

Bob, age 17

Bob, age 24




The copy constructor allows your program to make copies of instances when doing calculations. It is a key method. During calculations, instances are created to hold intermediate results. They are modified, cast and destroyed without you being aware. This is why those methods can be useful even for simple objects (see chapter 14.).

In all the examples above, the methods are defined inside the class definition. That automatically makes them inline methods.




BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

3G S

JAIL BREAK

iPHONE

BILL GATES

StEvE JoBs

steve jobs

STEVE JOBS

Steve Jobs

Love Country

SD

Burroughs

Lift

Joseph Johnson

Apple Rainbow

Apple Blue

Apple Laser Printer