c++ - What make upcasting and downcasting illegal -


during lecture student said upcasting , downcasting lacks logic , illegal. how teacher got confused , agreed , said review , lecture again dont know wrong code , there scenario illegal.

#include <iostream> using namespace std; class base { public:         int a,b;         base(){         a=0;         b=1;} }; class derived : public base { public:     int c,d;     derived(){     c=2;     d=3;     } }; int main(){     derived der;     base baseob;     derived *derptr=new derived;     derptr=(derived*)&baseob;     base *baseptr=new base;     baseptr=&der; } 

edited: scratch above code working on pointed out memory leak occurring(stupid of me not see that) here new code want know legal or not? (dynamic cast taught after no examples of dynamic cast please)

#include <iostream>  using namespace std;  class employee  {  public:  employee(string fname, string lname, double sal)  {  firstname = fname;  lastname = lname;  salary = sal;  }  string firstname;  string lastname;  double salary;  void show()  {  cout << "first name: " << firstname << " last name: " << lastname << " salary: " << salary<< endl;  }  void addbonus(double bonus)  {    salary += bonus;  }  };  class manager :public employee  {  public:  manager(string fname, string lname, double sal, double comm) :employee(fname, lname, sal)  {  commision = comm;  }  double commision;  double getcomm()  {  return commision;  }  };  

for downcasting

    int main() { employee e1("ali", "khan", 5000); //object of base class      //try cast employee      manager manager* m3 = (manager*)(&e1); //explicit downcasting      cout << m3->getcomm() << endl; return 0; } 

for upcasting

int main()      {      employee* emp; //pointer base class object      manager m1("ali", "khan", 5000, 0.2); //object of derived class      emp = &m1; //implicit upcasting      emp->show(); //okay because show() base class function      return 0;      }  

regardless of leaking memory, not recommend way of casting. provided example uses c-style casts, though work, can lead undefined behaviour (if types hierarchy mismatches).

upcasting via baseptr=&der; fine, although more common call simply:

base* baseptr = new derived(); 

this work if created object of derived class.

downcasting should performed via dynamic_cast, e.g.:

base* baseptr = new base(); derived* derptr = dynamic_cast<derived>(baseptr); // fail, derptr == nullptr 

if pointer cannot cast derived (really - extended in regards base) class, dynamic_cast return nullptr. should check that. in example above, casting fail , derptr == nullptr resolves true.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -