Noah Chai
Noah Chai

Reputation: 11

Trouble overwriting inherited static const members

I have two classes. The base class is fruit,and the derived class is apple. I use type strings to identify the type of the classes.However,when I tried to access the type() function of an instance of class apple to get the return of its type string, I got the base class' type string "fruit" rather than "apple".What should I do to fix this? Here's my code:

#include <string>
class fruit
{
public:
    std::string type();
private:
    static const std::string _typeStr;
}
const std::string fruit::_typeStr = "fruit";
std::string fruit::type()
{
    return _typeStr;
}
class apple:public fruit
{
private:
    static const std::string _typeStr;
}
const std::string apple::_typeStr = "apple";

In file main.cpp:

#include <iostream>
#include "fruit.h"
int main()
{
apple::apple a;
cout<<a.type()<<endl;
return 1;
}

In outputs:

fruit

Upvotes: 0

Views: 65

Answers (2)

Michael Surette
Michael Surette

Reputation: 711

One option is to set the non-static variable _typeStr in the constructor.

#include <iostream>
#include <string>

using namespace std;

class fruit
{
public:
    fruit()
        : _typeStr("fruit"){};
    fruit(const char *type)
        : _typeStr(type){};
    std::string type();

protected:
    const std::string _typeStr;
};

std::string fruit::type()
{
    return _typeStr;
}

class apple : public fruit
{
public:
    apple()
        : fruit("apple"){};
};

int main()
{
    apple a;
    cout << a.type() << endl;
    return 1;
}

Upvotes: 1

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

This cannot work.

    std::string type();

This is a fixed fucntion that will return fruit type. PEriod.

If you want to do things your way, use virtual functions:

#include <string>
class fruit
{
public:
    virtual ~fruit() = default;
    virtual const std::string& type(); // (return _typeStr)
private:
    static const std::string _typeStr;
}
const std::string fruit::_typeStr = "fruit";
std::string fruit::type()
{
    return _typeStr;
}
class apple:public fruit
{
public:
    const std::string& type() override; // (return _typeStr; will return apple::_typeStr)
private:
    static const std::string _typeStr;
}
const std::string apple::_typeStr = "apple";

And implement the virtual functions to return the string of each class.

Upvotes: 0

Related Questions