Private Versus Protected during inheritance - C++ Class

C++ examples for Class:Inheritance

Description

Private Versus Protected during inheritance

Demo Code

#include <iostream> 
   /* w w w  . j  a v a 2 s . co  m*/
enum COLOR { RED, BLUE, WHITE, BLACK, EE, YELLOW }; 
   
class Pet 
{ 
public: 
    // constructors 
    Pet(): age(2), weight(5) {} 
    ~Pet(){} 
   
    // accessors 
    int getAge() const { return age; } 
    void setAge(int newAge) { age = newAge; } 
    int getWeight() const { return weight; } 
    void setWeight(int newWeight) { weight = newWeight; } 
   
    // other member functions 
    void speak() const { std::cout << "Pet sound!\n"; } 
    void sleep() const { std::cout << "Shhh. I'm sleeping.\n"; } 
   
protected: 
    int age; 
    int weight; 
}; 
   
class Dog : public Pet 
{ 
public: 
    // constructors 
    Dog(): color(RED) {} 
    ~Dog() {} 
   
    // accessors 
    COLOR getBreed() const { return color; } 
    void setBreed(COLOR newBreed) { color = newBreed; } 
   
    // other member functions 
    void wagTail() { std::cout << "Tail wagging ...\n"; } 
    void begForFood() { std::cout << "Begging for food ...\n"; } 
   
private: 
    COLOR color; 
}; 
   
int main() 
{ 
    Dog fido; 
    fido.speak(); 
    fido.wagTail(); 
    std::cout << "Fido is " << fido.getAge() << " years old\n"; 
    return 0; 
}

Result


Related Tutorials