Home | | Computer Science 11th std | C++: Invocation of constructors

Example Programs in C++ - C++: Invocation of constructors | 11th Computer Science : Chapter 14 : Classes and objects

Chapter: 11th Computer Science : Chapter 14 : Classes and objects

C++: Invocation of constructors

There are two ways to create an object using parameterized constructor • Implicit call • Explicit call

Invocation of constructors

 

There are two ways to create an object using parameterized constructor

• Implicit call

• Explicit call

 

Implicit call

 

In this method ,the parameterized constructor is invoked automatically whenever an object is created. For example simple s1(10,20); in this for creating the object s1 parameterized constructor is automatically invoked.

 

Explicit call

 

In this method ,the name of the constructor is explicitly given to invoke the parameterized constructor so that the object can be created and initialized .

 

For example

simple s1=simple(10,20);        //explicit call

Explicit call method is the most suitable method as it creates a temporary object ,the chance of data loss will not arise.A temprory object lives in memory as long as it is being used in an expression.After this it get destroyed.

 

Illustration14.25 to illustrate implicit call and explicit call

#include<iostream>

using namespace std;

class simple

{

private:

int a, b;

public:

simple(int m,int n)

{

a= m ;

b= n;

cout<< "\n Constructor of class-simple invoked for implicit and explicit call"<<endl;

}

void putdata()

{

cout<<"\nThe two integers are... "<<a<<'\t'<< b<<endl;

cout<<"\n The sum of the variables "<<a<<" + "<<b<<" = "<<a+b; }

};

int main()

{

simple s1(10,20);                  //implicit call

simple s2=simple(30,45);         //explicit call

cout<<"\n\t\tObject 1\n";

s1.putdata();

s2.putdata();

return 0;

}

Explicit call to constructor creates a temporary instance

Output:

Constructor of class-simple invoked for implicit and explicit call

Constructor of class-simple invoked for implicit and explicit call

Object 1 

The two integers are... 10 20

The sum of the variables 10 + 20 = 30

Object 2 

The two integers are... 30 45

The sum of the variables 30 + 45 = 75

 

Tags : Example Programs in C++ , 11th Computer Science : Chapter 14 : Classes and objects
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 14 : Classes and objects : C++: Invocation of constructors | Example Programs in C++

Related Topics

11th Computer Science : Chapter 14 : Classes and objects


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.