A pointer to base class cannot operate member object only exist in its derived class?

The following won't work

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

class base {
public:
	int b;
};

class derived:public base {
public:
	int d;
};

int main() {
	derived D;
	base *  bp=& D;

	cout<<D.b<<endl;
	cout<<D.d<<endl;

	cout<<bp->b<<endl;
        cout<<bp->d<<endl;//error message: d cannot be resolved
	return 0;
}


then What can I do to let the more universal pointer to use that specific new object?

if this cannot be done, then I feel the usage of polymorphism is very limited!!! Hope I am wrong.
Last edited on
Its very limited becuase you're using it wrong :p Polymorphism is to be used with virtual functions. Here is an example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class base {
public:
	virtual int func(int x) = 0;
};

class derived :public base {
public:
	int func(int x)
	{
		cout << "My age is ";
		return x;
		cout << endl;
	}
};

int main() {
	derived D;
	base *  bp = &D;

	cout << bp->func(19) << endl;

	system("pause");
	return 0;
}


output:

My age is 19


https://www.youtube.com/watch?v=tvC1WCdV1XU&list=PLAE85DE8440AA6B83&ab_channel=thenewboston

Watch video 55-57.
Thanks!
Topic archived. No new replies allowed.