inheritance

Nov 10, 2011 at 3:07pm
Hi all, I would like to do something as follows, though I don't know if it is even possible. Here is a simple code
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
#include <iostream>

template<typename T>
class A
{
public:
  typedef T atype;
  A() {std::cout << "constructor A\n";}
  ~A() {std::cout << "destructor A\n";}
  T m() const { return 1; }
  void print() const
  {
  std::cout << m() << std::endl;
  }
};

template<typename T>
class B : public A<T>
{
public:
  B(): A<T>::A() {std::cout << "constructor B\n";}
  ~B() {std::cout << "destructor B\n";}
  T m() const { return 2; }
};

int main()
{
A<double> a;
B<double> b;
a.print();
b.print();
return 0;
}
The output that the above peace of code gives is
constructor A
constructor A
constructor B
1
1
destructor B
destructor A
destructor A
but I would like to see
constructor A
constructor A
constructor B
1
2
destructor B
destructor A
destructor A
Basically, I want the print method which is inherited in the B class to evoke m() method which is declared in B class and not the one from the A class. I guess I have to use virtual functions, but I don't know which methods should be made virtual.
Nov 10, 2011 at 3:42pm
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
#include <iostream>

template<typename T>
class A
{
public:
  typedef T atype;
  A() {std::cout << "constructor A\n";}
  ~A() {std::cout << "destructor A\n";}
  T m() const { return 1; }
  void print() const
  {
  std::cout << m() << std::endl;
  }
};

template<typename T>
class B : public A<T>
{
public:
  B(): A<T>::A() {std::cout << "constructor B\n";}
  ~B() {std::cout << "destructor B\n";}
  T m() const { return 2; }
void print() const
  {
  std::cout << m() << std::endl;  //adding print function  in the derived class 
  }
};

int main()
{
A<double> a;
B<double> b;
a.print();
b.print();
return 0;
}
Nov 10, 2011 at 3:48pm
That is precisely what I would like to avoid. The code I have posted is just a huge simplification of my real code. The print function is much, much longer in my real code and I have couple of classes that are derived from A. So even though, this is the simplest solution I would like to avoid it, because than I would have to duplicate the print() method in all my derived classes.
Last edited on Nov 10, 2011 at 3:49pm
Nov 10, 2011 at 4:18pm
make 'm' virtual:

1
2
3
4
5
6
7
8
9
10
11
12
13
template<typename T>
class A
{
public:
  typedef T atype;
  A() {std::cout << "constructor A\n";}
  ~A() {std::cout << "destructor A\n";}
  virtual T m() const { return 1; }  // <- make it virtual
  void print() const
  {
  std::cout << m() << std::endl;
  }
};
Topic archived. No new replies allowed.