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();
};
3
  • 1
    You already are assigning a value with x = 1; - I'm not sure what else you want to do Commented Nov 26, 2021 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? Commented Nov 26, 2021 at 20:44
  • @UnholySheep my bad the problem was the wrong object declaration of ex2 so it didn't work. Ty tho :) Commented Nov 26, 2021 at 20:50

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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";
};

3 Comments

Actually, you made another, mor important change to the original code than providing a default value for xi.
Hi @churill, do you mean the foo ex2; part?
Excatly :) foo ex2(); (like in the original) would also fail in your version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.