Open In App

Constructors in C++

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor.

Syntax of Constructors in C++

The prototype of the constructor looks like this:

<class-name> (){
...
}
Cpp-constructors

Characteristics of Constructors in C++

  • The name of the constructor is the same as its class name.
  • Constructors are mostly declared in the public section of the class though they can be declared in the private section of the class.
  • Constructors do not return values; hence they do not have a return type.
  • A constructor gets called automatically when we create the object of the class.

For a comprehensive guide on constructors and other class-related topics, explore our Complete C++ Course, which covers constructors, destructors, and other OOP features in depth.

Types of Constructor Definitions in C++

In C++, there are 2 methods by which a constructor can be declared:

1. Defining the Constructor Within the Class

<class-name> (list-of-parameters) {
// constructor definition
}

2. Defining the Constructor Outside the Class

<class-name> {

// Declaring the constructor
// Definiton will be provided outside
<class-name>();

// Defining remaining class
}

<class-name>: :<class-name>(list-of-parameters) {
// constructor definition
}

Example:

Constructor within Class
// Example to show defining
// the constructor within the class

#include <iostream>
using namespace std;

// Class definition
class student {
    int rno;
    char name[50];
    double fee;

public:
    /*
    Here we will define a constructor
    inside the same class for which
    we are creating it.
    */
    student()
    {
        // Constructor within the class

        cout << "Enter the RollNo:";
        cin >> rno;
        cout << "Enter the Name:";
        cin >> name;
        cout << "Enter the Fee:";
        cin >> fee;
    }

    // Function to display the data
    // defined via constructor
    void display()
    {
        cout << endl << rno << "\t" << name << "\t" << fee;
    }
};

int main()
{

    student s;
    /*
    constructor gets called automatically
    as soon as the object of the class is declared
    */

    s.display();
    return 0;
}
Constructor outside Class
// defining the constructor outside the class
#include <iostream>
using namespace std;
class student {
    int rno;
    char name[50];
    double fee;

public:
    /*
    To define a constructor outside the class,
    we need to declare it within the class first.
    Then we can define the implementation anywhere.
    */
    student();

    void display();
};

/*
Here we will define a constructor
outside the class for which
we are creating it.
*/
student::student()
{
    // outside definition of constructor

    cout << "Enter the RollNo:";
    cin >> rno;
    cout << "Enter the Name:";
    cin >> name;
    cout << "Enter the Fee:";
    cin >> fee;
}

void student::display()
{
    cout << endl << rno << "\t" << name << "\t" << fee;
}

// driver code
int main()
{
    student s;
    /*
    constructor gets called automatically
    as soon as the object of the class is declared
    */

    s.display();
    return 0;
}


Output:

Enter the RollNo:11
Enter the Name:Aman
Enter the Fee:10111
11 Aman 10111

Note: We can make the constructor defined outside the class as inline to make it equivalent to the in class definition. But note that inline is not an instruction to the compiler, it is only the request which compiler may or may not implement depending on the circumstances.

Types of Constructors in C++

Constructors can be classified based on in which situations they are being used. There are 4 types of constructors in C++:

  1. Default Constructor: No parameters. They are used to create an object with default values.
  2. Parameterized Constructor: Takes parameters. Used to create an object with specific initial values.
  3. Copy Constructor: Takes a reference to another object of the same class. Used to create a copy of an object.
  4. Move Constructor: Takes an rvalue reference to another object. Transfers resources from a temporary object.

1. Default Constructor

A default constructor is a constructor that doesn’t take any argument. It has no parameters. It is also called a zero-argument constructor.

Syntax of Default Constructor

className() {
// body_of_constructor
}

The compiler automatically creates an implicit default constructor if the programmer does not define one.

2. Parameterized Constructor

Parameterized constructors make it possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object.

Syntax of Parameterized Constructor

className (parameters...) {
// body
}

If we want to initialize the data members, we can also use the initializer list as shown:

MyClass::MyClass(int val) : memberVar(val) {};

3. Copy Constructor

A copy constructor is a member function that initializes an object using another object of the same class.

Syntax of Copy Constructor

Copy constructor takes a reference to an object of the same class as an argument.

ClassName (ClassName &obj)
{
// body_containing_logic
}

Just like the default constructor, the C++ compiler also provides an implicit copy constructor if the explicit copy constructor definition is not present.

Here, it is to be noted that, unlike the default constructor where the presence of any type of explicit constructor results in the deletion of the implicit default constructor, the implicit copy constructor will always be created by the compiler if there is no explicit copy constructor or explicit move constructor is present.

4. Move Constructor

The move constructor is a recent addition to the family of constructors in C++. It is like a copy constructor that constructs the object from the already existing objects., but instead of copying the object in the new memory, it makes use of move semantics to transfer the ownership of the already created object to the new object without creating extra copies.

It can be seen as stealing the resources from other objects.

Syntax of Move Constructor

className (className&& obj) {
// body of the constructor
}

The move constructor takes the rvalue reference of the object of the same class and transfers the ownership of this object to the newly created object.

Like a copy constructor, the compiler will create a move constructor for each class that does not have any explicit move constructor.

Conclusion

In summary, constructors in C++ are special methods that initialize objects of a class. They can be default (with no arguments), parameterized (with specific values), copy constructors (for deep copying), or move constructors (for resource transfer). Understanding these types and their usage is essential for effective object initialization and management.

If you are confused about what you should study next on this topic, refer to the article – A Comprehensive Guide to Constructors in C++: Everything You Need to Know

Frequently Asked Questions on C++ Constructors

What Are the Functions That Are Generated by the Compiler by Default, If We Do Not Provide Them Explicitly?

The functions that are generated by the compiler by default if we do not provide them explicitly are:

  1. Default Constructor
  2. Copy Constructor
  3. Move Constructors
  4. Assignment Operator
  5. Destructor

Can We Make the Constructors Private?

Yes, in C++, constructors can be made private. This means that no external code can directly create an object of that class.

How Constructors Are Different from a Normal Member Function?

A constructor is different from normal functions in following ways: 

  • Constructor has same name as the class itself
  • Default Constructors don’t have input argument however, Copy and Parameterized Constructors have input arguments
  • Constructors don’t have return type
  • A constructor is automatically called when an object is created.
  • It must be placed in public section of class.
  • If we do not specify a constructor, C++ compiler generates a default constructor for object (expects no parameters and has an empty body).

Can We Have More Than One Constructor in a Class?

Yes, we can have more than one constructor in a class. It is called Constructor Overloading.

Related Articles:

 



Previous Article
Next Article

Similar Reads

When Does Compiler Create Default and Copy Constructors in C++?
A constructor is a special type of member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) is created. There are 3 types of constructors in C++ Default ConstructorCopy constructorParameterized ConstructorIn C++, the compiler creates a default constructor if we d
3 min read
C++ Interview questions based on constructors/ Destructors.
1. What is destructor? Ans. Destructor is a member function which is called when an object is deleted/destroyed or goes out of scope. class String { private: char* s; int size; public: String(char*); // constructor ~String(); // destructor }; 2. What is the purpose of using a destructor in C++? Ans. The main purpose of destructor is to free all the
3 min read
How to initialize Array of objects with parameterized constructors in C++
Array of Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects. Syntax: ClassName ObjectName[number of objects]; Different methods to initialize the Array of objects with parameterized constructors:
6 min read
Inheritance and Constructors in Java
Constructors in Java are used to initialize the values of the attributes of the object serving the goal to bring Java closer to the real world. We already have a default constructor that is called automatically if no constructor is found in the code. But if we make any constructor say parameterized constructor in order to initialize some attributes
3 min read
When are Constructors Called?
When are the constructors called for different types of objects like global, local, static local, dynamic? 1) Global objects: For a global object, constructor is called before main() is called. For example, see the following program and output: C/C++ Code #include<iostream> using namespace std; class Test { public: Test(); }; Test::Test() { c
3 min read
A Comprehensive Guide to Constructors in C++: Everything You Need to Know
In C++, constructors are special member functions of a class that are automatically called when an object of the class is created. They are used to initialize objects. Constructors have the same name as the class and do not have a return type. What is a Constructor?A constructor is a special member function of a class that initializes objects of th
15+ min read
Types of Constructors in C++
In C++, there are several types of constructors, each serving a different purpose. Constructors can be classified based on in which situations they are being used. There are 4 types of constructors in C++: Default Constructor: No parameters. They are used to create an object with default values.Parameterized Constructor: Takes parameters. Used to c
13 min read
Importance of Constructors in C++
Constructors are special member functions in C++ that are invoked automatically when an object of a class is created. Their primary role is to initialize objects. In this article, we will learn all the factors that makes the constructor important in C++. Table of Content Initialization of ObjectsResource ManagementOverloading ConstructorsDefault Co
8 min read
std::move in Utility in C++ | Move Semantics, Move Constructors and Move Assignment Operators
Prerequisites: lvalue referencervalue referenceCopy Semantics (Copy Constructor)References: In C++ there are two types of references- lvalue reference:An lvalue is an expression that will appear on the left-hand side or on the right-hand side of an assignment.Simply, a variable or object that has a name and memory address.It uses one ampersand (
9 min read
Default Constructors in C++
A constructor without any arguments or with the default value for every argument is said to be the Default constructor. A constructor that has zero parameter list or in other sense, a constructor that accepts no arguments is called a zero-argument constructor or default constructor. If default constructor is not defined in the source code by the pr
4 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Types of Operating Systems
An Operating System performs all the basic tasks like managing files, processes, and memory. Thus, the operating system acts as the manager of all the resources, i.e. resource manager. Thus, the operating system becomes an interface between the user and the machine. It is one of the most required software that is present in the device. Operating Sy
11 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Example: Here, The data is stored in key: value pairs in dictionaries, which makes it easier to find values. [GFGTABS] Python Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(Dict) [/GFGTABS] Output {1: 'Geeks', 2: 'For', 3: 'Geeks'} Python dic
10 min read
vector erase() and clear() in C++
The std::vector::erase() and std::vector::clear() methods in C++ are used to remove elements from the std::vector container. They are the member function of std::vector class defined inside <vector> header file. In this article, we will learn how to use vector::erase() and vector::clear() in C++. Table of Content vector::erase()vector::clear(
3 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth
6 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
10 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Exceptions in Java
Exception Handling in Java is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. What are Java Exceptions?In Java, Exception is an unwanted or
10 min read
Interfaces in Java
An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods. What are Interfaces in Java?The interface in Java is a mechanism to achieve abstraction. Traditionally, an interface cou
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is defined inside the <set> header file. Syntax: std:
7 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::
9 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
9 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two nu
7 min read
Practice Tags :
three90RightbarBannerImg