user142019
user142019

Reputation:

A public struct inside a class

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

Upvotes: 5

Views: 22384

Answers (4)

Jorg B Jorge
Jorg B Jorge

Reputation: 1119

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 {

};

Upvotes: 3

AshleysBrain
AshleysBrain

Reputation: 22641

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'

Upvotes: 1

Pieter
Pieter

Reputation: 2912

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.

Upvotes: 12

kennytm
kennytm

Reputation: 523784

 class Human : public Creature {

C++ defaults to private inheritance for classes.

Upvotes: 7

Related Questions