OOP

The result is xx:48 xx:48.Could someone explain me the result? Thanks
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
  class Bike
{
private:
	char* brand;
public:
	Bike()
	{
		brand = "xx";
	}
	virtual void move(int t1)
	{
		cout << brand << ":" << t1*12 << " ";
	}
	
};
class EBike :public Bike
{
public: 
	EBike() :Bike()
	{

	}
	void move(int t2)
	{
		Bike::move(t2 * 2);
	}
};
void display(Bike& a, EBike& b)
{
	a.move(2);
	b.move(2);
}
void main()
{
	
	EBike b1, b2;
	display(b1, b2);
	//return 0;

}
Try running this and following the steps

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
#include <iostream>                    // <===== please use headers
#include <string>           
using namespace std;

class Bike
{
private:
	string brand;                         // <===== better as string
public:
	Bike()
	{
                cout << "Entering constructor of Bike" << endl;
		brand = "xx";
	}
	virtual void move(int t1)
	{
                cout << "Entering move() for Bike with argument t1=" << t1 << "       Note that t1*12 = " << t1 * 12 << endl;
		cout << brand << ":" << t1*12 << " " << endl;
	}
	
};
class EBike :public Bike
{
public: 
	EBike() :Bike()
	{
                cout << "Entering constructor of EBike" << endl;
	}
	void move(int t2)
	{
                cout << "Entering move() for EBike with argument t2=" << t2 << "       Note that t2*2 = " << t2 * 2 << endl;
		Bike::move(t2 * 2);
	}
};
void display(Bike& a, EBike& b)
{
        cout << "Entering display()" << endl;
        cout << "calling a.move(2)" << endl;
	a.move(2);
        cout << "calling b.move(2)" << endl;
	b.move(2);
}
int main()                   // <===== please use int main()
{
	
	EBike b1, b2;
	display(b1, b2);
	//return 0;
}
Last edited on
I think what confuses you is that b1 which is of type EBike is passed to display() as Bike yet when display() calls move() on it, b1 still acts as EBike! i.e. it outputs 48 and not 24!

However that's the whole idea of polymorphism. It's that base class can take form of any class that extended it.
http://www.cplusplus.com/doc/tutorial/polymorphism/

In your example Bike takes form of EBike.

EBike replaces its parent's void move() with its own void move() but Bike* can still point to EBike (and Bike& can still reference to EBike) regardless that the implementation of move() is different

That's what it means that Bike can take form of EBike.
Last edited on
Topic archived. No new replies allowed.