When a new object is created, initially garbage values are stored in the variables. Hence variables should be properly initialized at the time of creation of the objects, to avoid unwanted results. To initialize or define an object, C++ provides a special method called constructors,. The declaration /definition of this function must be within the class definition. A constructor function is automatically called along with the object declaration and it initializes all the data members in the object


Rules for writing constructor
  • A constructor name should be same as the class name
  • It is declared in the public section.
  • It can be defined code inside or outside the class, as any other method.
  • It is declared with no return type (not event void).

Characteristics of constructors
  • The constructor function has the following characteristics
  • Constructors are declared in the public section.
  • They do not invoked automatically when the objects ae created.
  • They do not have return type and hence they cannot return values.
  • They cannot be inherited
  • A derived class constructor can call the base class constructors.
  • Constructors can be overloaded
  • They can have default arguments
  • They cannot be declared const or volatile
  • They cannot be declared static or virtual.
  • We cannot refer to their address

Program

#include<iostream>
class number
{   
    int a,b;
public:
    number(void);
    readdata();
    displaydata();
};

number::number(void)
{
     a=0;b=0;
}

void number :: readdata()
{
     cout<<”\n enter the values of a and b:;
     cin>>a>>b;
}

void number::displaydata()
{
    cout<<”\n the values of a and b are ;
    cout<<a=<<a<<,  <<b=<<b;
}

int main()
{
    number n;
    n.displaydata();
    n.readdata();
    n.displaydata();
}

Output:

The values a and b are a=0, b=0
Enter the values of a and b: 10 20
The values a and b are a=10, b=20


Types of constructors

A class can be declared/defined with different types of constructors. Constructors can be classified as default constructor, parameterized constructors, copy constructor and dynamic constructor. Future, constructors can be overloaded and constructors with default arguments can be used.


Other recommended posts of Constructor and Destructor

Posted by Unknown On 23:53 No comments

0 comments:

Post a Comment

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube

Blog Archive

Contact Us


Name

E-mail *

Message *