Do I have to explicitly typecast for conversion from derived to base???

#include<stdio.h>
#include<iostream>
using namespace std;

class base
{
public:
void display()
{
cout<<"base"<<endl;
}

};

class derived
{
public:
void display()
{
cout<<"derived"<<endl;
}
};


int main()
{
base*bptr;
derived dobj;
bptr=(base*)&dobj; //it says error if I simply write bptr=&dobj;
bptr->display();
return 0;
}


In the above program...it shows error if I simply write bptr=&dobj and it works fine if I explicitly mentions the cast likle above....in most programming books ..they dont cast explicitly for this conversion(derived address into bae pointer)...then why this compiler is showing it as error??
and one more clarification, can we cast base object into derived object if we explicitly cast?


can you tell me which all conversions are legal?
derived object address into base pointer
derived object into base object
base object address into derived pointer
base object into derived object
and please let me know which all above conversions need explict casting and which all conversions can de done with simple assignment?

thanks in advance
Prasad
Your class "derived" isn't actually derived from "base".

It should look like "class derived : public base", but it's just "class derived".
Your derived is not a derived class from base.

Change your code to:
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
//#include<stdio.h> Remove this.
 #include<iostream>
 using namespace std;

 class base 
 {
 public:
 void display()
 {
 cout<<"base"<<endl;
 }

 };

 class derived  : public base // class derived is inherited from base
 {
 public:
 void display()
 {
 cout<<"derived"<<endl;
 }
 };


 int main()
 {
 base*bptr;
 derived dobj;
 bptr=&dobj; //now it should work.
 bptr->display();
 return 0;
 }
Last edited on
Topic archived. No new replies allowed.