Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - construction of an object inside a class

I'm fairly new to C++, and I'm not sure about this one. Have a look at the following example which sums up my current problem.

class Foo {     //stuff };  class Bar {     Foo foo; }; 

So Bar constains a full Foo object, not just a reference or pointer. Is this object initialized by its default constructor ? Do I need to explicitly call its constructor, and if so, how and where ?

Thanks.

like image 692
SolarBear Avatar asked May 11 '09 20:05

SolarBear


People also ask

What is constructor inside class?

A class constructor is a special member function of a class that is executed whenever we create new objects of that class. A constructor will have exact same name as the class and it does not have any return type at all, not even void.

Which construction is called automatically when we create an object of the class?

A constructor in C++ is a special method that is automatically called when an object of a class is created.

Can you create an object inside its class?

We can use it to create the Object of a Class. Class. forName actually loads the Class in Java but doesn't create any Object. To create an Object of the Class you have to use the new Instance Method of the Class.


1 Answers

It will be initialized by its default constructor. If you want to use a different constructor, you might have something like this:

class Foo {     public:      Foo(int val) { }     //stuff };  class Bar {     public:     Bar() : foo(2) { }      Foo foo; }; 
like image 88
Frank Schwieterman Avatar answered Sep 25 '22 09:09

Frank Schwieterman