markzzz
markzzz

Reputation: 47995

Is there a way to init/call CTOR in the .cpp?

I've these pointer declarations objects within the .h:

ILFO *pLFOPianoRoll1, *pLFOPianoRoll2, *pLFOPianoRoll3;

which I init in the .cpp with:

pLFOPianoRoll1 = new ILFO(this, 8, 423, kParamIDPianoRollLFO1, 0);
pLFOPianoRoll2 = new ILFO(this, 8, 542, kParamIDPianoRollLFO1, 1);
pLFOPianoRoll3 = new ILFO(this, 8, 661, kParamIDPianoRollLFO1, 2);

but I'd like to avoid pointers here (I learnt that "if you don't need them, don't use them"), and just use variable/class (due to manual management of the memory later).

But how can I decleare the variable of the object in the .h (such as ILFO mLFOPianoRoll1) and than call the CTOR on the .cpp?

Upvotes: 0

Views: 56

Answers (2)

paweldac
paweldac

Reputation: 1184

You can use initialization list for this purpose.

#include <iostream>
#include <string>
using namespace std;

class A
{
public:
    A(int a_) : a(a_) { }

    void print() 
    {
        std::cout << "A: " << a << std::endl;
    }

    int a;
};

class B
{
public:
    B() : a(1), a2(3) {}
    A a;
    A a2;
};

int main() {
    B bObj;
    bObj.a.print();
    bObj.a2.print();
   return 0;
}

https://ideone.com/C7Vx1X

Upvotes: 1

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133092

In order to simply declare the variable, use the extern keyword:

extern ILFO obj; //just declaration, no constructor is called.

in the .cpp file

ILFO obj(blah, blah, blah); //definition

This, of course, if you're talking about namespace-scope (including global) variables. If you're talking about class members, then you must know that the constructors of the members are not invoked until the constructor of the class. You can pass the parameters to the constructors in the constructor initialization list.

Upvotes: 1

Related Questions