CBSE Computer Science - Revision Tour(Solved)

CBSE Guess > eBooks > Class XII > CBSE Computer Science Constructors And Destructors Solved Revision Tour By Mr. Ravi Kiran

COMPUTER SCIENCE CONSTRUCTORS AND DESTRUCTORS

Previous Index Next

Temporary Instances: A temporary instance lives in the memory as long it is being used or referenced in an expression and after this it dies. A temporary instance will not have any name. The explicit call to a constructor also allows you to create a temporary instance or temporary object. The temporary instances are deleted when they are no longer referenced.

Eg:

class Sample
{
int i,j;
public:
sample (int a, int b)
{
i=a;
j=b;
}
void print ( )
{
cout<<i<<j<<”\n”;
}
----
----
};
void test ( )
{
Sample S1(2,5);
//An object S1 created
S1.print ( );
//Data values of S1 printed
Sample (4,9).print ( );
//Data values of a temporary
//sample instance printed
}

The primitive (fundamental) types also have their own constructors. When no values are provided, they use their default constructors but when you provide initial values, the newly created instance is initialized with the provided value.

Eg:

int a,b,c;
//Default constructor used
int i(3), j(4), k(5); //i,j,k initialized

c) Copy Constructor: A copy constructor is a constructor of the form classname(classname &). The compiler will use the copy constructor whenever you initialize an instance using values of another instance of same type.

Eg:
Sample S1; //Default constructor used Sample S2=S1; //Copy constructor used. Also Sample S2(S1); In the above code, for the second statement, the compiler will copy the instance S1 to S2 member by member. If you have not defined a copy constructor, the compiler automatically, creates it and it is public. A copy constructor takes a reference to an object of the same class an argument.

Eg:

class Sample
{
int i,j;
public:
Sample (int a, int b) //Constructor
{
i = a;
j = b;
}
Sample (Sample &s) //Copy Constructor
{
i=s.i;
j=s.j;
cout<<”Copy constructor
Working\n”;
}
void print( )
{
cout<<i<<”\t”<<j<<”\n”;
}
-----
-----
};
void main( )
{
Sample S1(4,9);
//S1 initialized first constructor used
Sample S2(S1);
//S1 copied to S2. Copy constructor called.
Sample S3=S1;
//S1 coped to S3. Copy constructor called again.
-----
-----
}


Previous Index Next

CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )