Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call constructor after declaration

Tags:

c++

This may be a very basic question. How can I call a constructor after variable declaration? For example, this is a working code:

// in header
class Bar
{
    SomeClass *foo;
public:
    Bar();
}

// in .cpp
Bar::Bar()
{
    foo = new SomeClass(1, 2, 3);
}

But how can I change this so foo is not a pointer?

Thanks!

like image 708
Martin Heralecký Avatar asked Mar 13 '26 19:03

Martin Heralecký


2 Answers

If your foo is defined inside class then use constructor initializer list as follows:

class X {
   X() : foo(1,2,3) {}
   SomeClass foo;
};

If you need to calculated arguments to foo-s constructor then it becomes more difficult. You could add functions which would calculate your values ie.:

class X {
   X() : foo(initX(),initY(),initZ()) {}
   SomeClass foo;

   static int initX() { return 1;}
   static int initY() { return 2;}
   static int initZ() { return 3;}
};

but this is not always possible - i.e. it depends on how you calculate your values. (static is intentional as you should better not use not fully constructed class members).

You could also pass those values as constructor parameters.

like image 89
marcinj Avatar answered Mar 15 '26 10:03

marcinj


If you're declaring this outside a class it will be a global variable. To have it constructed in a .cpp file you should probably declare it extern in the header and then use the constructor you want when you declare it in the cpp

SomeModule.h:

extern SomeClass foo;

SomeModule.cpp:

SomeClass foo(1, 2, 3);

If it's a member variable of a class then you can use the constructor you want by explicitly initialising the variable in the member initialisation list of the constructor

OtherClass.h:

class OtherClass
{
    SomeClass foo;
    public:
      OtherClass();
}

OtherClass.cpp:

OtherClass::OtherClass() : foo(1, 2, 3) {};

If wanting to initialize in the middle of the code like with the pointer case then you can just let it initialize with the default constructor and copy over the value with the one you want at the same place as you would the pointer like so

foo = SomeClass(1, 2, 3);
like image 28
FrankM Avatar answered Mar 15 '26 10:03

FrankM



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!