📖 Samacheer Kalvi · 11th TN - English Medium · Computer Science · Page 239question

Unit IV · Part 6

Chapter 3: 4 · Computer Science

of a class is declared or created. The main function of the constructor is ) To allocate memory space to the object and ) To initialize the data member of the class object There is an alternate way to initialize the class objects but in that case we have to explicitly call the member function. . Types of constructors There are different types of constructors.

• Default Constructors A constructor that accepts no parameter is called default constructor. For example in the class Data, Data ::Data() is the default constructor . Using this constructor Objects are created similar to the way the variables of other data types are created. If a class does not contain an explicit constructor (user defined constructor) the compiler automatically generate a default constructor.

• Parameterized Constructors A constructor which can take arguments is called parameterized constructor .This type of constructor helps to create objects with different initial values. This is achieved by passing parameters to the function. Example : Data :: Data(int,int); • Copy Constructors A constructor having a reference to an already existing object of its own class is called copy constructor. It is usually of the form Data (Data&), where Data is the class name.

A copy constructor can be called in meny ways: ) When an object is passed as a parameter to any of the member functions Example void Data::putdata(Data x); ) When a member function returns an object Example Data getdata() { } ) When an object is passed by reference to an instance of its own class For example, Data d1, d2 (d1); // d2(d1) calls copy constructor Chapter Page - - #include<iostream> using namespace std; class Data int i, j; public: int k; Data() cout<<"Non Parametrerized constructor"; i= ; j= ' Data(int a,int b) cout<<"Parametrerized constructor"; i=a; j=b' Data(Data &a) cout<<"Copy constructor"; i=a.i; j=b.j' void display() //member function cout<< i<<j; }; int main() Data d1,d2( , ),d3(d2); d1.display(); d2.display(); d3.display(); return ; Illustration . Types of constructor . Invocation of constructors There are two ways to create an object using parameterized constructor • Implicit call • Explicit call

Related topics

Have a question about this topic?

Get an AI answer grounded in your actual textbook — with the exact page reference.

Ask AI about this topic →