Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling constructor of a class member in constructor

Can I call constructor of a member in my Class's constructor?

let say If I have a member bar of class type foo in my class MClass. Can I call constructor of bar in MClass's constructor? If not, then how can I initialize my member bar?

It is a problem of initializing members in composition(aggregation).

like image 687
shampa Avatar asked Oct 13 '11 23:10

shampa


People also ask

Can you call a constructor of a class inside another constructor?

The invocation of one constructor from another constructor within the same class or different class is known as constructor chaining in Java. If we have to call a constructor within the same class, we use 'this' keyword and if we want to call it from another class we use the 'super' keyword.

How do you call a constructor from another constructor in Java?

To call one constructor from another constructor is called constructor chaining in java. This process can be implemented in two ways: Using this() keyword to call the current class constructor within the “same class”. Using super() keyword to call the superclass constructor from the “base class”.

Can I call a constructor in another constructor C++?

No, in C++ you cannot call a constructor from a constructor.

How can we call the constructor of the class?

Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.


1 Answers

Yes, certainly you can! That's what the constructor initializer list is for. This is an essential feature that you require to initialize members that don't have default constructors, as well as constants and references:

class Foo {   Bar x;     // requires Bar::Bar(char) constructor   const int n;   double & q; public:   Foo(double & a, char b) : x(b), n(42), q(a) { }   //                      ^^^^^^^^^^^^^^^^^^^ }; 

You further need the initializer list to specify a non-default constructor for base classes in derived class constructors.

like image 171
Kerrek SB Avatar answered Oct 07 '22 01:10

Kerrek SB