RockOGOlic
RockOGOlic

Reputation: 150

Implementation file (.cpp) for a class with member initialization

My question must be simple, but I cannot find a right way to split the constructor with initialized members to .h and .cpp (definition and implementation), files.

If, say, I have:

    class Class {

    public: 
    Class (int num, float fl ... ) : _num(num), _fl(fl) {}
    ...

    private:
    int _num;
    float _fl;

    };

How do I implement the constructor in .cpp file? If, after member initialization (in header file) I put semi-colon - compiler complains. If I keep { }, the .cpp file will the re-define the constructor, which is also wrong. I can, of course, write down the definition explicitly. So that the .h file is:

    Class (int num, float fl ... );

and .cpp :

    Class (int num, float fl ... ) {
    _num = num; 
    _fl = fl;
    }

But is there a way to keep the member initialization in the header file? Thanks in advance! Also, in professional coding, what would be preferred?

Upvotes: 0

Views: 1036

Answers (2)

sanoj subran
sanoj subran

Reputation: 406

It is better to keep the declaration and definition of class members separately in header and source files unless you are dealing with template parameters. You can keep member initialization separately in the following way.

Header file
------------------

class A {
public:
A(int x, float y );

private:
int _x;
float _y;
};

And then in the source file, it can be defined as,

A::A(int x, float y ) : _x(x), _y(y) {}

Upvotes: 1

Jean-Marc Volle
Jean-Marc Volle

Reputation: 3333

You need to have members init and construction implementation in the .cpp

Class::Class (int num, float fl ... ):_num(num),_fl(fl) 
{
  // whatevever other init task you want to do goes here
}

Upvotes: 4

Related Questions