0

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?

RockOGOlic
  • 150
  • 1
  • 7

2 Answers2

4

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
}
Jean-Marc Volle
  • 3,113
  • 1
  • 16
  • 20
  • 1
    In professional coding or any coding this is what you do. There is no way to spilt it. To add, the purpose of a header is to be just definitions, no actual implementation. It acts kind of like "This works but I'm not telling you how it does it". So putting the member initialisation there would defeat that purpose. – Derek C. Apr 29 '20 at 16:15
  • Thank you Jean-Marc Volle and Derek C. That is quite clear : ) In the end, the header must only contain definitions, that's true! – RockOGOlic Apr 29 '20 at 16:23
  • 1
    They're declarations. The thing shown above is a definition. – Asteroids With Wings Apr 29 '20 at 16:34
  • @AsteroidsWithWings apparently, there is no universal agreement on how to call what in this case. But I agree that logically, .h are for declarations and .cpp are for definitions, where you define what you declared. Would initially write that, but found online that some call it other way around. Anyway, declaration/definition is the only correct way, IMHO. – RockOGOlic Apr 29 '20 at 18:56
  • @RockOGOlic The standard is very clear about what they're called. If you find something online that reversed those terms, you should steer clear of that site. – Asteroids With Wings Apr 29 '20 at 18:58
1

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) {}
sanoj subran
  • 401
  • 4
  • 11