pãgës

Wednesday, September 29, 2010

C++ Constructors


A constructor is a function that initializes the members of an object. A constructor only knows how to build an object of its own class. If no constructor is supplied then a default one is created by the compiler without any parameters. There must always be a constructor, even if it is the default and empty. If you supply a constructor with parameters then a default will NOT be created.
Like any other function constructor can also be overloaded. A Default constructor is a constructor that can be called with no arguments.


There is a special constructor called copy constructor. Copy constructor creates a new object as a copy of an existing object. The first argument of such a constructor is a reference to an object of the same type as is being constructed. If you don’t define your own copy constructor, the compiler will provide you one.


Normally if you have any pointer or reference variable in your class, then you should define your own copy constructor and overloaded assignment operator to do the deep copy. Otherwise it will do the shallow copy. We will discuss about deep and shallow copy in separate post soon.


One important point to note is that we cannot pass object by value to the copy constructor. According to the C++ standard the copy constructor must take a reference to the same class.


Constructors cannot be virtual. Since virtual allows us to call a function knowing only the interfaces and not the exact type of the object. To create an object you need complete information. In particular, you need to know what you want to create exactly. Hence call to a constructor can't be virtual. We will see about virtual functions and vtable in forthcoming posts.





class class_Name
{
Private:
Int var;
Public:
class_Name() {} // Default Constructor
class_Name(int x):var(x) {} //Overloaded Constructor
class_Name(class_Name const &obj){} //Copy constructor
};


Where class_Name() is the default constructor for class class_Name. class_Name(int x)is the overloaded constructor which takes an integer as argument and assigns it to variable ‘a’. class_Name(class_Name const &obj) is the copy constructor.




Example:


#include
Using std::cout;
Class ConstructorExample
{
Int x;
Public:
ConstructorExample ():x(10){}//Default
ConstructorExample(int a):x(a){}//Overloaded
ConstructorExample(ConstructorExample const &obj){//Copy constructor
X = obj.x;
}
Void Display(){
Cout<<”Value of x is “< }
};
Int main()
{
ConstructorExample obj1;
Obj1. Display ();
ConstructorExample obj2(25);
Obj2. Display ();
ConstructorExample obj3(obj2);
Obj3. Display ();
}



ConstructorExample () is the default constructor. The constructor must have the public access in order to create the object of that class type.


In default constructor x is initialized with value 10 in the member initialization list of the constructor ConstructorExample ().


ConstructorExample (int a) is the overloaded constructor. It takes integer an as argument and assigns it to variable ‘x’.


ConstructorExample(ConstructorExample const &obj) is the copy constructor. It builds new ConstructorExample object from existing ConstructorExample object.


And we have an public member function called void Display () which takes and returns nothing, Also prints the message with value of x.


In main function we are declaring the object obj1 of type ConstructorExample. It uses the default constructor ConstructorExample () to build this object. So it will initialize the variable x with default value 10.


The object obj2 of type ConstructorExample. It uses the overloaded constructor ConstructorExample (int a) to build this object. So it will initialize the variable x with the given value 25.


And we are declaring the object obj3 of type ConstructorExample. It uses the copy constructor ConstructorExample (ConstructorExample const &obj) to build this object. So it will initialize the variable x with the existing obj2.x value 25.



Now we are calling the member function Display () on object obj1, obj2 and obj3 to check the available values.

save the above file as ConstructorExample.cpp

compile the above program using GNU g++ compiler (Linux).

g++ ConstructorExample.cpp -o ConstructorExample

The output file name will be ConstructorExample. Run the file using ./ConstructorExample

You can see the output below

Value of x is 10
Value of x is 25
Value of x is 25

Things to note when coding the constructors

  • The constructor must have the same name as class.

  • The constructor should not have any return type (not even void).

  • Constructors cannot be virtual.

  • Storage specifiers and Storage qualifiers are not applicable to class Constructors.

  • Copy constructor is called


    • When an object is created from another object of the same type

    • When an object is passed by value as a parameter to a function

    • When an object is returned from a function



Happy Coding :)

Tuesday, September 14, 2010

C++ Classes



Class is a user defined data type. classes helps to achieve Data abstraction and encapsulation. Instead of holding only data, it can hold both data and functions. An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.

Classes are generally declared using the keyword class, with the following format:

class class_Name
{
Access_specifier_1:
Member1;
Access_specifier_2:
Member2;
};

Where class_Name is a valid identifier for the class. The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers.

An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights that the members following them.

  • private members of a class are accessible only from within other members of the same class or from their friends.

  • protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.

  • Finally, public members are accessible from anywhere where the object is visible.


By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access.

Example:

#include
using std::cout;
class HelloWorld
{
int x;
public:
HelloWorld():x(10){}
void Print(){
cout<<”Hello World ! Value of x is “< }
};
int main()
{
HelloWorld Obj;
Obj. Print();
}

Here HelloWorld is the name of the class. Since the default access specifier is private , the integer variable x has Here private access. That means it cannot be accessed outside the class.

HelloWorld() is the name of the constructor. Since it is under public access specifier, the constructor has the public access. The constructor must have the same name as the class and it should not return any value. The constructor must have the public access in order to create the object of that class type. We can see about constructors in details in forthcoming sessions.

Also note that the member x is initialized with value 10 in the member initialization list of the constructor. We can see about the initialization list in forthcoming posts.

And we have an public member function called void Print() which takes and returns nothing, Also prints the message with value of x.

In main function we are declaring an object of type HelloWorld. Here obj is the variable name and HelloWorld is the abstract data type name.

Now we are calling the member function Print() on object obj. Since Print() is the public member function, it can be accessed from outside the class.

save the above file as HelloWorldClass.cpp

compile the above program using GNU g++ compiler (Linux).
g++ HelloWorldClass.cpp -o HelloWorldClass

The output file name will be HelloWorldClass . Run the file using ./HelloWorldClass

You can see the output below

Hello World ! Value of x is 10

Things to note when coding the classes

  • The class declaration must end with a semi-colon.

  • C++ is case sensitive class != Class

  • class's constructor function must have the same name as the class, and no return type (not even void).

  • Member initialization list can be used only with constructors.


Happy Coding :)

C++ Hello World Tutorial

This C++ Hello World tutorial is written for beginning C++ students without previous C++ programming experience. It is traditional writing "Hello World" Program when start learning any new programming languages.


#include
using namespace std;
int main()
{
cout << "Hello World!" << endl;
cout << "Welcome to C++" << endl;
}


iostream is a header file which is used for input/output in the C++ programming language. It is part of the C++ standard library.

using namespace std; keeps you from having to type std::cout each time that output is needed.
The cout object is of type ostream, it is available in std namespace.

int main() is the main function which executes first, before any other code.

cout << is the output statement and strings need quotation marks. cout overloads the left bit-shift operator to make it perform an operation completely unrelated to bitwise operations.

C++ statements and edded with semicolon. So end the cout line with a ; (semicolon)

The << endl means that the next cout will have a new output line. endl is an output manipulator that writes a newline and flushes the buffer, ensuring that the data is output immediately. An alternative to the newline character is `\n`.

save the above file as HelloWorld.cpp
compile the above program using GNU g++ compiler (Linux).
g++ HelloWorld.cpp -o HelloWorld
The output file name will be HelloWorld . Run the file using ./HelloWorld
You can see the output in two Lines

Hello World!
Welcome to C++


Happy Coding :)