Home > database >  Cpp/C Assign Default value to default constructor
Cpp/C Assign Default value to default constructor

Time:11-27

This seems like a really easy question but I can't find a working solution(maybe it is the rest of the code too). So basically how do you assign a value to an object created with the default constructor, when the custom constructor has that variable as a parameter? (hopefully this is understandable)

Maybe clearer: The code below only works if I write foo ex2(2) instead of foo ex2() inside the main function. So how do I assign a default value to x if the object is created with the default constructor

class foo {

public:
    int y;
    int x;
    static int counter;

    foo()
    {
        y = counter;
        counter  ;
        x = 1;
    };

    foo(int xi) 
    {
        y = counter;
        counter  ;
        x = xi;
    };

};

int foo::counter = 0;

int main()
{

    foo ex1(1);
    foo ex2();

    std::cout << ex1.y << "\t" << ex1.x << "\n";
    std::cout << ex2.y << "\t" << ex2.x << "\n";
    std::cin.get();
};

CodePudding user response:

This record

foo ex2();

is not an object declaration of the class foo.

It is a function declaration that has the return type foo and no parameters.

You need to write

foo ex2;

or

foo ( ex2 );

or

foo ex2 {};

or

foo ex2 = {};

CodePudding user response:

As said above. Then to assign a default value:

class foo {
public:
    int y;
    int x;
    static int counter;
    foo(int xi = 1) : x(xi)
    {
        y = counter;
        counter  ;
    };
};
int foo::counter = 0;

int main()
{
    foo ex1(3);
    foo ex2;

    std::cout << ex1.y << "\t" << ex1.x << "\n";
    std::cout << ex2.y << "\t" << ex2.x << "\n";
};
  • Related