Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP Constructor question C++

Let's say that I have two classes A and B.

class A
{
    private:
        int value;
    public:
        A(int v)
        {
            value = v;
        }
};

class B
{
    private:
        A value;
    public:
        B()
        {
            // Here's my problem
        }

}

I guess it's something basic but I don't know how to call A's constructor.

Also the compiler demands a default constructor for class A. But if A has a default constructor than wouldn't the default constructor be called whenever I declare a variable of type A. Can I still call a constructor after the default constructor has been called? Or can I declare an instance of a class and then call a constructor later?

I think this could be solved using pointers but can that be avoided ?

I know that you can do something like this in C#.

EDIT: I want to do some computations in the constructor and than initialize the classes. I don't know the values beforehand.

Let's say I'm reading the value from a file and then I initialize A accordingly.

like image 652
EyyoFyber Avatar asked Sep 29 '26 02:09

EyyoFyber


2 Answers

The term you are looking for is initializer list. It is separated from the constructor body with a colon and determines how the members are initialized. Always prefer initialization to assignment when possible.

class A
{
    int value;

public:

    A(int value) : value(value) {}
};

class B
{
    A a;

public:

    B(int value) : a(value) {}
}

I want to do some computations in the constructor and than initialize the classes. I don't know the values beforehand.

Simply perform the computation in a separate function which you then call in the initializer list.

class B
{
    A a;

    static int some_computation()
    {
        return 42;
    }

public:

    B() : a(some_computation()) {}
}
like image 91
fredoverflow Avatar answered Sep 30 '26 15:09

fredoverflow


You use an initialization list to initialize the member variables.

public:
    B() : value(4) {   // calls A::A(4) for value.
    }
like image 31
kennytm Avatar answered Sep 30 '26 15:09

kennytm



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!