Inheritance Help - first time

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
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

class Child{
public:
	string setName(string name){name = name;}
	string getName(){return name;}
private:
	string name;
};

class Parent : Child{
public:
	string setPName(string parent){pName = parent;}
	string getParent(){return pName;}
	Child kid;
private:
	string pName;
};


int main(){
	Parent dad;
	dad.kid.setName("Sandy");
	dad.setPName("David");
	cout << "The dads childs name is " << dad.kid.getName();
	cout << "The dads name is " << dad.getParent();
	return 0;
}


I am getting a Segmentation 11 Fault in my console when I run, However it is building just fine. Any reason for this? I'd like some help pointing it out so I don't make the same simple mistake! Thanks guys. Just messing around with inheritance for nearly the first time
closed account (zb0S216C)
Your logic seems to be a little messed up. "::Parent" is deriving from "::Child" which implies that the parent is-a child. Kinda' weird, no?

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
class Human
{
  public:
    Human( std::string const &InitialName = "John Doe" )
      : Name( InitialName )
    { }

  private:
    std::string Name;

  public:
    std::string const &QueryName( ) const
    {
      return( Name );
    }
};

class Child : public Human // Child is-a human
{
  public:
    Child( std::string const &InitialName = "John Doe" )
      : Human( InitialName )
    { }

  private:
    using Human::Name;

  public:
    using Human::QueryName;
};

class Parent : public Human // Parent is-a human
{
  public:
    Parent( std::string const &InitialName = "John Doe" )
      : Human( InitialName )
    { }

  private:
    using Human::Name;

  public:
    using Human::QueryName;
};

See the logic?

Also, The "using" statements don't have to be there, but I put them there to emphasise the inheritance. I recommend reading this: http://www.cplusplus.com/doc/tutorial/inheritance/

Wazzak
Last edited on
setName and setPName are supposed to return a string, yet they do not return anything.

name = name on line 8 is extremely ambiguous. Change the function parameter's name to something different.

Also, there really isn't anything that takes advantage of inheritance in your code.
Last edited on
Topic archived. No new replies allowed.