Why can't my base class pointer work the same way as a basic pointer?
Mar 6, 2018 at 1:59am UTC
Hi!
As the title why can't my base pointer work the same way as a normal pointer?
In other words why instead of using the superclass pointer I have to use the derived class,in order my code to work properly and not crash?
and why this
1 2 3 4 5 6
vehicle *motors;
Car gaia;
motors = &gaia;
*(motors) = Car::Car(3.7, 6, 'I' , 'G' , 205, 8000, "Sedan" );
motors->Printme();
is not equal to this?
1 2 3 4 5 6
int a;
int *p;
p = &a;
*p = 10;
std::cout << *p<<"\n" ;
Thank you for answering!
Last edited on Mar 6, 2018 at 1:59am UTC
Mar 6, 2018 at 11:33am UTC
> why can't my base pointer work the same way as a normal pointer?
it does work the same way.
> and why this
> is not equal to this?
they are equivalent
1 2 3 4 5
vehicle *motors; int a; //declare pointer and object
Car gaia; int *p;
motors = &gaia; p = &a; //pointer points to the object
*(motors) = Car::Car(3.7, 6, 'I' , 'G' , 205, 8000, "Sedan" ); *p = 10; //dereference pointer, assigment
motors->Printme(); std::cout << *p<<"\n" ; //dereference pointer, printing
> in order my code to work properly and not crash?
¿what crash? ¿where is the code that caused the crash?
Mar 6, 2018 at 12:44pm UTC
Slice and dice 'em.
That example of yours has an int and a pointer to int. The other code has a Car and a pointer to vehicle.
Lets try something else:
1 2 3 4
vehicle zetor;
Car fiat(3.7, 6, 'I' , 'G' , 205, 8000, "Sedan" );
zetor = fiat;
What happens on line 4? Does it differ from
*(motors) = fiat;
?
This ain't legal, but:
1 2 3 4 5
double a;
int *p;
p = &a;
*p = 3.14;
std::cout << *p<<"\n" ;
The p is a pointer to int. Therefore, *p is an int. Its location is within the first bytes of double a.
Surely the assignment overwrites only sizeof(int) bytes with an int value?
The printout shows that same int. What would be the value of a (if code were legal)?
Topic archived. No new replies allowed.