Search code examples
c++oopheader-files

default parameters in .h and .cpp files


COMPILER: g++ 4.7.2

Ok. So I am confused about default parameters in .h and .cpp files. It is mentioned in many places( including this site) that default parameters can be added only in .h files and not in .cpp files. However, this code proves it wrong:

test1.h

#pragma once

#include <iostream>
using namespace std;

class Class{
public:
    Class(int, int, int=1);
};

test1.cpp

#include "test1.h"

Class::Class(int a, int b=2, int c)
{
    cout<<a<<" "<<b<<" "<<c<<endl;
}

int main()
{
    Class a(1);
    return 0;
}

Now, according to what I have tested, default parameters can be added to .cpp files. However, the following restrictions hold:

  1. The default parameters present in .cpp and .h file should not overlap. i.e. Class(a, b, c=1) (in .h file) and Class::Class(a,b,c=2)( in .cpp file) is invalid.

    It is a well known rule that once default parameters have been added, all the variables declared after that must also contain default values. Lets call this the defpara rule. Now,

  2. The variables stated in the function declaration( .h file) should obey the defpara rule i.e. Class(a, b=2, c) (in .h file) is invalid irrespective of what's declared in .cpp file.

  3. If one considers the variables having default values (as an intersection of default values in .h and .cpp files), it would follow the defpara rule. i.e. Class(a, b, c=1) (in .h file) and Class::Class(a,b=2,c)( in .cpp file) is valid. But Class(a, b, c=1) (in .h file) and Class::Class(a=2,b,c)( in .cpp file) is invalid.

So....I am right, wrong???


Solution

  • This only works because your main function is also in your test.cpp file, so it sees the default argument specified in your class' implementation. If you put your main function in a separate file that only includes test.h, this code will not compile.

    Another way of looking at it is, when some other includes test.h, all that code sees is what is declared in test.h, so default arguments put elsewhere will not be used.