1

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();
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Finn
  • 47
  • 4
  • 1
    You already are assigning a value with `x = 1;` - I'm not sure what else you want to do – UnholySheep Nov 26 '21 at 20:43
  • 1
    You should turn on all your compilers warnings: `warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse]` -> [What is the purpose of the Most Vexing Parse?](https://stackoverflow.com/questions/14077608/what-is-the-purpose-of-the-most-vexing-parse) – Lukas-T Nov 26 '21 at 20:44
  • @UnholySheep my bad the problem was the wrong object declaration of ex2 so it didn't work. Ty tho :) – Finn Nov 26 '21 at 20:50

2 Answers2

1

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 = {};

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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";
};
lakeweb
  • 1,859
  • 2
  • 16
  • 21