박태규
박태규

Reputation: 27

c++ Inheritance same ouput

An unexpected problem occurred while studying inheritance. I don't know why the output is the same. specified default values for each class.

#include <iostream>
#include <string>
using namespace std;
class Drink{
private:
    string kind;
public:
    Drink(string k="drink")
    {
        kind=k;
    }
    void print() 
    {
        cout<<kind<<endl;
    }
};
class Coffee : public Drink{
public:
    Coffee(string k) : Drink(k="coffee")
    {}
    void print() 
    {
        Drink::print();
    }   
};
class Americano :public Coffee{
public:
    Americano(string k) : Coffee(k="americano")
    {}
    void print() 
    {
        Coffee::print();
    }
};
int main()
{
    Coffee c("");
    Americano a("");
    c.print();
    a.print();
    return 0;
}

I want to print out coffee americano. How can I print out other results?

Upvotes: 0

Views: 34

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

You're replacing the values of the derived constructors' arguments.
Default values belong in the parameter list, not the initializer list.

There is also no point in a member function that just calls an inherited member function and does nothing else.

Try this:

class Coffee : public Drink {
public:
    Coffee(string k="coffee") : Drink(k) {}
};

class Americano : public Coffee {
public:
    Americano(string k="americano") : Coffee(k) {} 
};

int main()
{
    Coffee c;
    Americano a;
    c.print();
    a.print();
}

Upvotes: 2

Related Questions