0% found this document useful (0 votes)
11 views2 pages

Single Inheritence

The document defines an Animal base class and Dog derived class to demonstrate inheritance and polymorphism in C++. The Animal class defines eat() and sleep() methods while the Dog class overrides sleep() and adds bark() and displayBreed() methods.

Uploaded by

Ankur Prajapati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Single Inheritence

The document defines an Animal base class and Dog derived class to demonstrate inheritance and polymorphism in C++. The Animal class defines eat() and sleep() methods while the Dog class overrides sleep() and adds bark() and displayBreed() methods.

Uploaded by

Ankur Prajapati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

#include <string>

// Base class

class Animal {

private:

std::string name;

public:

Animal(const std::string& n) : name(n) {}

void eat() {

std::cout << name << " is eating." << std::endl;

void sleep() {

std::cout << name << " is sleeping." << std::endl;

};

// Derived class

class Dog : public Animal {

private:

std::string breed;

public:

// Constructor for Dog class, calling the base class constructor explicitly

Dog(const std::string& n, const std::string& b) : Animal(n), breed(b) {}

void bark() {

std::cout << "Woof! Woof!" << std::endl;


}

// Overriding the sleep method from the base class

void sleep() {

std::cout << "The dog named " << getName() << " is sleeping." << std::endl;

// Additional method specific to the Dog class

void displayBreed() {

std::cout << "Breed: " << breed << std::endl;

};

int main() {

// Creating an instance of the Dog class

Dog myDog("Buddy", "Golden Retriever");

// Accessing methods from the base class

myDog.eat();

myDog.sleep(); // Calls the overridden sleep method in Dog class

// Accessing methods from the derived class

myDog.bark();

myDog.displayBreed();

return 0;

You might also like