Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this constructor correct?

Tags:

c++

I have two classes A and B, and in class A I have an member of type B:

class B {
    public:
        B(); //default constructor
};

class A {
    public:
        A(); //constructor
        B b;
};

This is the definition of class A's constructor:

A::A() : b()
{}

Here, I tried to initialize b using the initialization list. My question is, is this way to initialize b correct, or am I just creating another temporary object named b inside the constructor of A that has nothing to do with A::b?

like image 332
Chin Avatar asked Jan 28 '14 21:01

Chin


People also ask

Can we use this in constructor?

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .

What is constructor example?

Example 1: Java Constructor Main obj = new Main(); Here, when the object is created, the Main() constructor is called. And, the value of the name variable is initialized. Hence, the program prints the value of the name variables as Programiz .

Which is correct rules for constructor?

Rules to be remembered A constructor does not have return type. The name of the constructor is same as the name of the class. A constructor cannot be abstract, final, static and Synchronized. You can use the access specifiers public, protected & private with constructors.


1 Answers

This is correct. However, since b is of class type, the default constructor will be called automatically if b isn't mentioned in A::A's initialization list, so you don't need to mention it at all.

like image 132
Brian Bi Avatar answered Nov 02 '22 08:11

Brian Bi