Prometheus
Prometheus

Reputation: 147

C++ How to instantiate an object with parameterised constructor?

I have some understanding problems in C++ with parameterised constructors. If I have a class with one constructor which have two function parameters, how can i instantiate it in an other class header file?

For example:

public:
      MyFunction myfunction(param1, param2); //makes an error

How can i declare an object like this?

Upvotes: 0

Views: 83

Answers (4)

ForceBru
ForceBru

Reputation: 44838

As far as I understand, the problem is that MyFunction has only one constructor that only accepts two arguments.

You can use a pointer to that object and then initialize it in the constructor:

#include <memory>

class Something {
    public:
        std::shared_ptr<MyFunction> data;
        Something(int par1, int par2) {
            data = std::shared_ptr<MyFunction>(new MyFunction(par1, par2)); // here you go!
        }

        ~Something() {
            //delete data; no need to do this now
        }
};

Edit: added a smart pointer to follow rule of three.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234665

You need to write MyFunction myfunction; in the class declaration.

Then in the member initialiser list of the constructor to the class of which myfunction is a member, write

/*Your constructor here*/ : myfunction(param1, param2)
{
    /*the constructor body*/
}

The bit after the colon is the member initialiser list. param1 and param2 are obviously arguments to that constructor.

Upvotes: 3

Jarod42
Jarod42

Reputation: 217145

You have several ways:

struct P
{
    P(int a, int b) :a(a), b(b){}

    int a;
    int b;
};

struct S
{
    S() : p1(4, 2) {} // initializer list

    P p1;
    P p2{4, 2}; // since c++11
    P p3 = P(4, 2); // since c++11
};

Upvotes: 1

An option is having a predeclaration and a pointer to the class.

classA.h
class A
{
    public:
    A(a,b);
};

classB.h
class A;
class B{
    public:
    A* foo;
    B();
    ~B();
}

classB.cpp
#include classA.h
#include classB.h
B()
{
    foo=new A(a,b);
}
~B()
{
    delete(foo);
}

Upvotes: 0

Related Questions