l4x3
l4x3

Reputation: 17

How can I create an object inside a class in c++?

I want the object to be inside the class, but I can only do it inside a function:

This is basically what I want:

class Foo1 {

public:
   Foo1(int a, int b) { /*stuf..*/. }

}

class Foo2 {

Foo1 foo1(2, 1); // oject here

public:
   Foo2(int a, int b) { /*stuf...*/ }

}

Upvotes: 0

Views: 116

Answers (2)

anastaciu
anastaciu

Reputation: 23792

You can create the object and initialize it:

class Foo2
{
public:
    Foo1 foo1{2, 1}; // using curly brackets, object created and initialized

    // Or in the initializer list of the Foo2 constructor 
    // Foo1 foo1;
    // Foo2() : foo1(1,2){}
};

Let's assume your class Foo1 has 2 int members a and b, only for for test purposes because the object creation is the same:

class Foo1
{
public:
    int a, b; 
    Foo1(int a, int b) : a(a), b(b) {} // constructor
};

Test main:


int main()
{
    Foo2 foo2; // Foo2 object will have a Foo1 object inside

    std::cout << foo2.foo1.a << " "; // test print
    std::cout << foo2.foo1.b;        
}

Outupt

2 1

Live sample

Upvotes: 3

R Sahu
R Sahu

Reputation: 206557

If the code that you expect to go where you write

//stuf...

is simple, duplicate the code.

If not, create a function and call the function.

Example (Simple)

Duplicate the code.

class Foo1 {

public:
   Foo1(int a, int b) { int i = 0; int j = 0; }

}

class Foo2 {

Foo1 foo1(2, 1);

public:
   Foo2(int a, int b) { int i = 0; int j = 0; }

}

Example (Not Simple)

Use a function.

int complexFunction() { ... }

class Foo1 {

public:
   Foo1(int a, int b) { int i = complexFunction(); }

}

class Foo2 {

Foo1 foo1(2, 1);

public:
   Foo2(int a, int b) { int i = complexFunction(); }

}

Upvotes: 0

Related Questions