Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an instance of a class inside another class

Tags:

c++

Here is a simplified version of what I'm trying to do

class Firstclass
    {
    public:
    Firstclass(int x)
        {
        //do things with x;
        }
    };

class Secondclass
    {
    public:
    Secondclass()
        {
        Firstclass a(10);
        }

    void func()
        {
        //Do things with a
        }

    private:
    Firstclass a;
    };

So I have a class (Firstclass) with a constructor that takes an int argument. Now I'd like to create an instance of that class inside the constructor of another class (Secondclass).

The lines

private:
Firstclass a;

if what I'd do if a were just a variable instead of a class: mention it first such that I can use it elsewhere (in the function func() for instance). This doesn't seem to work with classes, because the compiler doesn't understand what the constructor of Secondclass is supposed to do.

How do I do this correctly?

like image 862
RobVerheyen Avatar asked Feb 26 '26 18:02

RobVerheyen


1 Answers

Initialize it through the member-initializer list:

Secondclass() : a(10) { }

This is required because Firstclass doesn't have a default constructor. Also, in-class initialization with parameters gets ambiguated with a function declaration, so you can do it in the class body. In C++11, this is resolved with aggregate-initialization:

Firstclass a{10};
like image 175
David G Avatar answered Mar 01 '26 10:03

David G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!