A Comprehensive Guide About Constructor In C++

The C++ programming language is a direct descendant of C, with added features such as type checking, object-oriented programming, and exception handling. It's commonly called a "better C." Bjarne Stroustrup was the one who came up with the idea.

C++ is a general-purpose programming language. ‘General-purpose’ here means that it is intended for its use in a wide range of applications

Free Course: JavaScript for Beginners

Learn the Basics of JavaScriptEnroll Now
Free Course: JavaScript for Beginners

What is a Constructor in C++? 

A function Object() { [native code] } is a class member function that initialises the class's properties. When an object (class instance) is created, it automatically names the builder constructor in C++. It is the unique role of the class member.

  A builder is distinct in the following ways from regular functions:

  • The builder is the same as the pupil
  • The builders have no sort of return
  • When an object is made, it immediately names a builder

If you don't define a function Object() { [native code] }, the constructor in  C++ compiler will build one for you (expects no parameters and has an empty body).

Now, look at a real-world example to learn about the different types of constructors in C++. Assume that you went to a store to purchase a marker. What are your choices for purchasing a marker? The first one requires you to go to a store and request a marker. So simply saying "give me a marker" means you haven't specified which brand or color you like, and you have said nothing other than "give me a marker." So when you simply say, "give me a marker," the person in charge would simply hand over whatever the most commonly sold marker is in the market or his store. And this is the concept of a default function Object() { [native code] }! The second option is to go to a store and request a red marker from the XYZ brand.

How Are the Builders Different From the Everyday Work of a Member?

Now that you know what a function Object() { [native code] } is, look at how it differs from a class's member function.

1) The function Object() { [native code] } has no return form. There is a return form for a member element.

2) When you build a class object, the function Object() { [native code] } is automatically named. You must call the member function directly using the class object.

3) If you don't define a function Object() { [native code] } in your class, the constructor in  C++ compiler creates one for you and inserts it into your code. The same cannot be said for member roles.

The Difference Between Constructors and Normal Member Function

Constructors

Normal member functions

The name of the function Object() { [native code] } will be the class name

The name of the function can be anything you want

The function Object() { [native code] } is only called once during object construction,

The function can be called several times with and without the object (static function).

constructors do not, even though they are empty

functions have return types

Types of Constructors in C++ and Their Use Cases

Now have a look at the different types of constructors in C++.

1. Default Constructor in C++

The default function Object() { [native code] } is one that doesn't take any arguments. It does not have any parameters.

Example:

// Cpp program to illustrate the

// concept of Constructors

#include <iostream>

using namespace std;

class construct

{

public:

            int a, b;

            // Default Constructor

            construct()

            {

                           a = 10;

                           b = 20;

            }

};

int main()

{

            // Default constructor called automatically

            // when the object is created

            construct c;

            cout << "a: " << c.a << endl

                           << "b: " << c.b;

            return 1;

}

Output:

2. Parameterised Constructor in C++

You may pass arguments into the constructor in  C++. These arguments are typically used to help initialize an object when it is built. Simply add parameters to a parameterized function Object() { [native code] } the same way you would to any other element. Use the parameters to initialize the object when defining the body of the constructor in C++.

// CPP program to illustrate

// parameterized constructors

#include <iostream>

using namespace std;

class Point

{

private:

            int x, y;

public:

            // Parameterized Constructor

            Point(int x1, int y1)

            {

                           x = x1;

                           y = y1;

            }

 

            int getX()

            {

                           return x;

            }

            int getY()

            {

                           return y;

            }

};

int main()

{

            // Constructor called

            Point p1(10, 15);

 

            // Access values assigned by constructor

            cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

            return 0;

}

Output:

 constructor-output

3. Copy constructor in C++

A copy function Object() { [native code] } is a member function that uses another object of the same class to initialise an object. Copy Constructor is discussed in depth later in this article.

When you define one or more non-default constructor in C++ ( with parameters) for a class, you must also define a default function Object() { [native code] }(without parameters), as the compiler will not have one in this case. It is not necessary, but it is considered best practise to define a default function Object() { [native code] } at all times.

Example:

// Illustration

#include "iostream"

using namespace std;

class point

{

private:

double x, y;

public:

// Non-default Constructor &

// default Constructor

point (double px, double py)

{

            x = px, y = py;

}

};

int main(void)

{

// Define an array of size

// 10 & of type point

// This line will cause error

point a[10];

// Remove above line and program

// will compile without error

point b = point(5, 6);

}

Output:

 constructor-output2

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Conclusion

This was a complete guide to help you understand the constructor in C++. These constructors are helpful in complex functions. Enroll in the Simplilearn course, and you can grow your skills with the help of our syllabus crafted from expertise. Follow up on the modules, and you will get the right results with the help of good faculty.

If you have completed this tutorial, there is a good chance that you might be looking to pursue a career in software development. If this is correct, you should definitely explore our Post Graduate Program in Full Stack Web Development in collaboration with Caltech CTME. This comprehensive applied learning program helps you gain high level expertise in over 30 of today’s most in-demand full stack development skills and tools. Designed to give real-world exposure with multiple projects, interactive labs, practical learning imparted by top practitioners, this program can prove to be the game changer in your climb up the ladder.

Have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, ASAP!

Happy learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.