Object with constructor as member of another object

Hello, I'm Angela and I'm new to the forum and the C++ programming language. Suppose I have a class Engine like this:

1
2
3
4
5
6
7
8
9
10
11
class Engine
{
public:
	Engine(/*some parameters here*/)
	{
		// Initialization of Engine's ctor here
	}
	// Some additional member functions 
private:
	// Some data members
};


And suppose I have a class car like this:

1
2
3
4
5
6
7
8
9
10
11
class Car
{
public:
	Car(/*some data here*/)
	{
		// Initialization of Car's ctor here...
	}
	// Some additional member functions 
private:
	Engine m_Engine; // <-- My question is related to this specific encapsulated object
};


The problem is that since I'm using a constructor to initialize my Engine object, I have to specify the parameters immediately right after I instantiate the object in the private field in order to initialize it:

1
2
3
4
public: 
        ...
private:
	Engine m_Engine(10.0f, 20.0f, 30.0f /*... you get the idea :)*/);


But, that kind of design doesn't seem very appealing to me and I'm trying to avoid it. One workaround I found myself doing was making the Engine object a pointer, then in the Car's constructor I allocate on the heap:

1
2
3
4
	Car::Car()
	{
		m_Engine = new Engine(); // Why am I being forced to allocate on the heap though? :(
	}


But I'm trying to minimize heap allocation and keep most of my objects on the stack instead because the object does not require a significant amount of bytes so I can safely store it on the stack. Another workaround I found is to have a kind of an "init()" method that does exactly what the ctor does and call it whenever I want to initialize my object. Though, this solution will have me flood nearly all my classes with init methods. Not ideal! :p

I understand that the constructor of an object is called the moment you instantiate an object. However, does anyone have a clever solution to instantiate objects with constructors in other objects without allocating on the heap or writing init() methods?

Thank you! I look forward to reading your thoughts on this matter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>

struct engine
{
    engine( int a, double b )
    { std::cout << "engine::engine(" << a << ',' << b << ")\n" ; }
};

struct car
{
    // the member initializer list specifies the initializers for
    // non-static data members its_engine and name
    // https://en.cppreference.com/w/cpp/language/initializer_list
    car( int a, double b, std::string n ) : its_engine(a,b), // initialise its_engine
                                            name(n) // initialise name
    { std::cout << "car::car\n" ; }

    engine its_engine ;
    std::string name ;
};

int main()
{
     car some_car( 12, 34.56, "seven" ) ;
}
I mean, of course it's that simple! hehe thank you sir! :)
Topic archived. No new replies allowed.