Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance class C++

I would like to call the parent constructor like this :

Character::Character(int x, int y, int h, int s, int a, char dir) : health(h), strength(s), armor(a), direction(dir){
    if(direction == 'N') {
        Visual('^', x, y);
    } else if(direction == 'S') {
        Visual('v', x, y);
    } else if(direction == 'W') {
        Visual('<', x, y);
    } else if(direction == 'E') {
        Visual('>', x, y);
    }
}

But it doesn't work well because it call the default constructor of the parent which is private

class Visual {
    private:
        Visual();
        Visual(const Visual &);
    protected:
        Position coordinate;
        char chara;
    public:
        Visual(char c, int x, int y);
};
like image 559
Jack Avatar asked Dec 19 '17 17:12

Jack


1 Answers

Create a function to convert the direction into a different character, and pass that to the public constructor:

namespace { //Anonymous Namespace for functions local to your .cpp files to avoid definition conflicts
    char convert_direction(char c) {
        switch(c) {
        case 'N': return '^';
        case 'S': return 'v';
        case 'E': return '>';
        case 'W': return '<';
        default: return '?';
        }
    }
}

Character::Character(int x, int y, int h, int s, int a, char dir) : 
    Visual(convert_direction(dir), x, y),
    health(h), strength(s), armor(a), direction(dir) 
{
}
like image 156
Xirema Avatar answered Sep 20 '22 05:09

Xirema