Site icon TestingDocs.com

Define C++ Class Constructor

Overview

In this tutorial, we will learn to define a C++ class constructor. When we define a class we can define its constructors.

C++ Class Constructor

A constructor is a special member function that is invoked to create a new object of that class. The name of the constructor function is always the same as the name of the class. C++ constructor has no return type.

The main use of a constructor is to initialize the member data variables of the newly created C++ object. Like other member functions, the constructor can be overloaded. A C++ class may have multiple overloaded constructors with different parameters.

 

 

If we omit the constructor in the class, the C++ compiler will generate a default no-arg constructor. The constructor with no parameters is called the default or no-arg constructor. If we define constructor/(s) in the class definition, the compiler will not supply this default constructor.

The code in a constructor definition typically sets the data members of the new object to valid default data values or to the values of the parameters passed into the constructor.

Sample C++ Program

 

/************************************
* C++ Class Constructor
* Filename: employee.cpp
* C++ Class Constructor Demo Program
* C++ Tutorials - www.TestingDocs.com
**************************************/
#include
#include
using namespace std;

// C++ class Employee
class Employee
{
public:
    // Employee C++ Class Constructor
    Employee(string name,double salary)
    {
        this->name=name;
        this->salary=salary;
    }

    Employee()
    {
        this->name="Default";
        this->salary=0.0f;
    }

    string getName()
    {
        return name; // return employees's name
    }

    double getSalary()
    {
        return salary; // return employees's name
    }

    void setName(string name)
    {
        this->name = name;// set employees's name
    }

    void setSalary(double salary)
    {
        this->salary = salary;// set employees's name
    }

private:
    string name;
    double salary;
};

int main()
{
    //Declare an Employee objects
    Employee emp1;
    Employee emp2("Mark",3000);
    //Invoke Setters
    emp1.setName("John");
    emp1.setSalary(2500.0);

    // Output
    cout << "C++ Tutorials - www.TestingDocs.com" << endl;
    cout << "Employee 1 = " << emp1.getName() << " | "<< emp1.getSalary() << endl;
    cout << "Employee 2 = " << emp2.getName() << " | "<< emp2.getSalary()<< endl;

    return 0;
} // end main


Program Output

C++ Tutorials – www.TestingDocs.com
Employee 1 = John | 2500
Employee 2 = Mark | 3000

C++ Tutorials

C++ Tutorials on this website:

https://www.testingdocs.com/c-coding-tutorials/

For more information on the current ISO C++ standard

https://isocpp.org/std/the-standard

Exit mobile version