tags:

views:

130

answers:

4

I am new to C++, and let's say I have two classes: Creature and Human:

/* creature.h */
class Creature {
private:
public:
    struct emotion {
        /* All emotions are percentages */
        char joy;
        char trust;
        char fear;
        char surprise;
        char sadness;
        char disgust;
        char anger;
        char anticipation;
        char love;
    };
};

/* human.h */
class Human : Creature {

};

And I have this in my main function in main.cpp:

Human foo;

My question is: how can I set foo's emotions? I tried this:

foo->emotion.fear = 5;

But GCC gives me this compile error:

error: base operand of '->' has non-pointer type 'Human'

This:

foo.emotion.fear = 5;

Gives:

error: 'struct Creature::emotion' is inaccessible
error: within this context
error: invalid use of 'struct Creature::emotion'

Can anyone help me? Thanks


P.S. No I did not forget the #includes

+5  A: 
 class Human : public Creature {

C++ defaults to private inheritance for classes.

KennyTM
+6  A: 

There is no variable of the type emotion. If you add a emotion emo; in your class definition you will be able to access foo.emo.fear as you want to.

Pieter
This, in combination with Kenny's answer did the job (Y)
Time Machine
Interesting to see how some people spot the inheritance problem first while others are more sensible to lacking variables :).
Pieter
+1 Pieter......
piemesons
A: 

Change inheritance to public and define a struct emotion member in Creature class (ex. emo).

So you can instantiate objects of Human class (ex. foo) and atrib values to its members like

foo.emo.fear = 5;

or

foo->emo.fear = 5;

Code changed:

/* creature.h */
class Creature {
private:
public:
    struct emotion {
        /* All emotions are percentages */
        char joy;
        char trust;
        char fear;
        char surprise;
        char sadness;
        char disgust;
        char anger;
        char anticipation;
        char love;
    } emo;
};

/* human.h */
class Human : public Creature {

};
Jorg B Jorge
A: 

Creature::emotionis a type, not a variable. You're doing the equivalent of foo->int = 5; but with your own type. Change your struct definition to this and your code will work:

struct emotion_t {  // changed type to emotion_t
        // ...
    } emotion;      // declaring member called 'emotion'
AshleysBrain