Total Noob: Working With Nested Class

Hello. First post. I've just recently started learning c++ by following the tutorial on this site, mainly for reference, and the occasional google search.

Just Started messing around with classes and structs. Now I'm kind of stuck on nested classes. I think it may be more my implementation and my understanding of the concept that is giving me trouble.

The error I receive when i try to compile:

on line 25 and 26
Invalid use of class Ship::Deck


my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

//ship class
class Ship {
    public:
        int Health;
        bool Fighter;
        bool Capital;

    //Nested class of ship
        class Deck{
            public:
                int Health,Oxygen;
                bool Fire,Sealed,Venting;
        }Command,Munitions,Reactor,Engines,Barracks,Hangar;
};
int main()
{
    Ship MyShip;

    MyShip.Fighter = true;
    cout << MyShip.Fighter << endl;

    MyShip.Deck.Command.Fire = true;        //] Compile errors
    cout << MyShip.Deck.Command.Fire;       //] --------------
    return 0;
}


So obviously i cant access the members of the nested class this way. So what am I doing wrong? Aren't the instances of type 'Deck' members of type 'Ship'? It seems like it should follow this type of chain that I've got going.
Last edited on
you can only create class objects inside another class but you can't define a class in them
Sure you can. The problem is the OP is including the name of the inner class in the dotted name:

MyShip.Deck.Command.Fire

should be

MyShip.Command.Fire

instead. Deck is Command's type, just like Ship is MyShip's type and bool is Fire's type.
Also, is making the Deck class public in this case necessary? I am not sure since you are trying to access an object of it outside of the ship class...
Oh yeah of course lol! Thanks filipe.
hanst99: Yeah I set it to private just to see and no go. It needs to be public because the call to .fire in int main is outside of 'ships' and 'decks' scope.

thanks again for all your quick responses!
#include <iostream>
using namespace std;
class Ship {
public:
int Health;
bool Fighter;
bool Capital;


class Deck{
public:
int Health,Oxygen;
bool Fire,Sealed,Venting;
};
};
int main()
{
Ship MyShip;

MyShip.Fighter = true;
cout<< MyShip.Fighter << endl;
cout<< MyShip.Capital<< endl;
Ship::Deck hi;
hi.Fire=true;
cout<<hi.Fire;
return 0;
}



Topic archived. No new replies allowed.