What is the difference between these two classes? In the second one protected: looking like it isn't doing anything at all, there's nothing under it umbrella.

class Tank
{
    protected:
        int wheels;
    public:
        void setWheels(int newWheels) { wheels = newWheels; }
        int getWheels() { return wheels; }
};

///////////////////////////////////////////////////////////////

class Tank
{
    private:
        int wheels
    protected:

    public:
        void setWheels(int newWheels) { wheels = newWheels; }
        int getWheels() { return wheels; }
};

Recommended Answers

All 7 Replies

Making things private vs protected deal with what access inherited classes have to members.

Public: everything has access to it.

Protected: Only acessible from the class or classes dervied from the class.

Private: Only accessible from the class.

You are correct in that the protected: declaration in class Tank does nothing. You could put static or instance methods or variables there, but since it is only succeeded by public: that is what access will be granted to following elements. Do note that you can multiple public, private, protected sections in a class header.

Thanks guys, here's another question. While my book was explaining the difference between public and private within a class it have me this line class Hombre : public Man but failed to explain why we would need to use public when creating a derived class.

private

The type or member can only be accessed by code in the same class or struct.

protected

The type or member can only be accessed by code in the same class or struct, or in a derived class.
class A 
{
public:
    int x;
protected:
    int y;
private:
    int z;
};

class B : public A
{
    // x is public
    // y is protected
    // z is not accessible from B
};

class C : protected A
{
    // x is protected
    // y is protected
    // z is not accessible from C
};

class D : private A
{
    // x is private
    // y is private
    // z is not accessible from D
};

DonnSchwartz - I get what public, private, & protected are doing inside a class but I don't understand why it need to me in the class decloration of a derived class as shown in my line above.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.