I do not understand inheritence

closed account (oG8U7k9E)
...
Last edited on
Because test2_class is calling test1_classes reply, which is referencing test1_classes's string thisreply, not test2_class's.
There are a couple of things you could do. You could pass the string up to the base class constructor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
using namespace std;
//------------------------------------------------------------------------------
namespace Test{
	struct Test1_class{
		Test1_class(string s = "hello")
			:thisreply(s){}
		string reply(){return thisreply;}
		string thisreply;
	};
//------------------------------------------------------------------------------
	struct Test2_class:Test1_class{
		Test2_class()
			:Test1_class("not hello"){}
	};
//------------------------------------------------------------------------------
}


But that would then allow an instance of Test1_class to be passed any string. Another way you could do it is to make the reply function virtual and override it in the base class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;
//------------------------------------------------------------------------------
namespace Test{
	struct Test1_class{
		Test1_class()
			:thisreply("hello"){}
		virtual string reply(){return thisreply;}
		string thisreply;
	};
//------------------------------------------------------------------------------
	struct Test2_class:Test1_class{
		Test2_class()
			:thisreply("not hello"){}
		string reply() { return thisreply; }
		string thisreply;
	};
//------------------------------------------------------------------------------
}
closed account (oG8U7k9E)
Thanks for the response, but I am afraid that I need to do quite a bit more reading. It does not make sense to me how one object can have two strings with the same name. I obviously need to have a better understanding of inheritance.
Or you could just modify the string directly in the derived class's constructor.
There is only one instance of the string.
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 <string>
using namespace std;

struct Foo
  {
  string m_reply;

  Foo(): m_reply( "Foo" ) { }

  string reply() const { return m_reply; }
  };

struct Bar: public Foo
  {
  Bar()
    {
    m_reply = "Bar";
    }
  };

int main()
  {
  Foo foo;
  Bar bar;

  cout << foo.reply() << endl;
  cout << bar.reply() << endl;

  return 0;
  }

Hope this helps.
closed account (oG8U7k9E)
Duoas, thank you, this is what I expected and what I wanted.
Last edited on
Topic archived. No new replies allowed.