During lecture some student said this upcasting and downcasting lacks logic and is illegal. Some how the teacher got confused and agreed and said he will review and do the lecture again but i dont know what is wrong with this code and is there a scenario where this would be 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 the above code it was something i was working on but like it was pointed out the memory leak was occurring(stupid of me not to see that) here is the new code now i only want to know is it legal or not? (dynamic cast was to be taught after this so 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 to cast an employee to
Manager Manager* m3 = (Manager*)(&e1); //explicit downcasting
cout << m3->getComm() << endl; return 0; }
For upcasting
int main()
{
Employee* emp; //pointer to base class object
Manager m1("Ali", "Khan", 5000, 0.2); //object of derived class
emp = &m1; //implicit upcasting
emp->show(); //okay because show() is a base class function
return 0;
}
Regardless of leaking memory, this is not the recommend way of casting. The provided example uses C-style casts, though they work, then can easily lead to undefined behaviour (if types hierarchy mismatches).
Upcasting via baseptr=&der;
is fine, although a more common call would be to simply:
base* baseptr = new derived();
This will always work if the created object is of a derived class.
Downcasting should be performed via a dynamic_cast
, e.g.:
base* baseptr = new base();
derived* derptr = dynamic_cast<derived>(baseptr); // will fail, derptr == nullptr
If a pointer cannot be cast into a derived (really - extended in regards to base) class, dynamic_cast
will return a nullptr. You should check for that. In the example above, the casting will fail and derptr == nullptr
resolves to true
.