C++ Constructors Part-I

A function Object() { [native code] } is a unique member function that bears the class’s name. There is no return type for the function Object() { [native code] }. The objects of their class are initialised using constructors. Every time an object is formed, constructors are automatically called.

Constructor characteristics in C++

  • In the public portion of the class, a function Object() { [native code] } ought to be declared.
  • When an object is created, they are automatically called.
  • They lack return types and are unable to return values.
  • It may accept standard arguments.

An example of how a constructor is used is

#include <iostream>
using namespace std;
 
class Employee
{
 
public:
    static int count; //returns number of employees
    string eName;
 
    //Constructor
    Employee()
    {
        count++; //increases employee count every time an object is defined
    }
 
    void setName(string name)
    {
        eName = name;
    }
 
    static int getCount()
    {
        return count;
    }
};
 
int Employee::count = 0; //defining the value of count
 
int main()
{
    Employee Harry1;
    Employee Harry2;
    Employee Harry3;
    cout << Employee::getCount() << endl;
}

Output:

3
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in