Constructor in C++ With Examples - DEEP CODER

Breaking

printf("Learn Deep Coding Here!!");

Constructor in C++ With Examples

Constructor in C++  :

constructor is a special type of member function that initialises an object automatically when it is created.
Compiler identifies a given member function is a constructor by its name and the return type.

Constructor has the same name as that of the class and it does not have any return type. Also, the constructor is always public.
//CONSTRUCTOR IN C++
class construct
{
private: 
 int x;

public:
 // Construct is a member Function Name is same as Class
 construct(): x(5)
 {
  // Body of constructor
 }

};

int main() //Main Function
{
 Construct c1;  //Object Declare
 ... .. ...

Constructor work In Program :

In the above pseudo code, Construct() is a constructor.
When an object of class Construct is created, the constructor is called "Automatically", and xis initialized to 5 .
You can also initialise the data members inside the constructor's body as below. However, this method is not preferred.
Construct()
{
   x = 5; //This Method is not preferred.
}

Example 1: Constructor in C++

// counter.cpp // object represents a counter variable #include <iostream> using namespace std; //////////////////////////////////////////////////////////////// class Counter { private: unsigned int count; //count public: Counter() : count(0) //constructor { /*empty body*/ } void inc_count() //increment count { count++; } int get_count() //return count { return count; } }; //////////////////////////////////////////////////////////////// int main() { Counter c1, c2; //define and initialize cout << “\nc1=” << c1.get_count(); //display cout << “\nc2=” << c2.get_count(); c1.inc_count(); //increment c1 c2.inc_count(); //increment c2 c2.inc_count(); //increment c2 cout << “\nc1=” << c1.get_count(); //display again cout << “\nc2=” << c2.get_count();
cout << endl; return 0; }
Output
I’m the constructor
I’m the constructor
 c1=0
 c2=0
 c1=1 
 c2=2

No comments:

Post a Comment