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
?
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 .
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With