segmentation fult while inheritance from derived to base class

Hi to everyone!!

I apologize if my question will appear a bit silly for someone. But I'm just a beginner.

My problem is that I get a segmentation faulior when I try to run a program which contains 1 derived class and 2 base classes. Input should be performed by derived class.

But this is where I get the mistake. Actually the program compiles but when I try to input the first value segmentation fault error occurs. And I can’t trace the mistake.

Does anybody know what might be the problem?
Many thanks in advance!


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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <string>
using namespace std;

class Animal{
  protected:
    string name;
  
  public:
    string getName()
    {cout<< "Pet's name "; cin>> name;}
    void dispName()
     {cout<< "My favorite pet is " << name;}
    void makeSound()
    {cout<< "This is my pet's sound...";}
};

class Dog:public Animal{
  
  public:
    void dispName()
    {cout<< "My pet dogis " << name;}
    void makeSound()
    {cout<< "Arf!arf!Arf!" ;}
    };

class Cat:public Animal{
  
  public:
    void dispName()
    {cout<< "My pet  cat is " << name;}
    void makeSound()
    {cout<< "Meow!Meow!Meow!";}
    };



int main(){
  
 Animal pet;
 Dog ido;
 Cat ikos;
 
 pet.getName();
 ido.getName();
 ikos.getName();
 
 
 pet.dispName();
 ido.dispName();
 pet.makeSound();
 ido.makeSound();
 ikos.dispName();
 pet.makeSound();
 ikos.makeSound();
  

  
 return 0; 
}


Last edited on
Compiling? getName method doesn't return a string?

You should use "virtual" keyword in base class(Animal class is base class. Dog and Cat classes are derived classes. So you have 2 derived and 1 base class) for overloaded methods.
Topic archived. No new replies allowed.