C
christian.pontesegger
Hi all,
lately I had a problem where I wanted to cast a basic class to a
derived type, which did not introduce any new members and did not
change any stuff with dynamically allocated memory. I just wanted to
add some methods to the class.
So my question is:
Is it valid C++ to create a basic class and to cast it to a derived
one the way I did in my example below? The example works fine for
MinGW, but I'm not sure if this is ABI dependent.
Example code:
<code>
#include <stdio.h>
class Basic {
public:
Basic(int a, int b) {
a_ = a;
b_ = b;
};
int getA() {
return a_;
};
int getB() {
return b_;
};
private:
int a_, b_;
};
class Derived : Basic {
public:
Derived(int a, int b) : Basic(a, b) {}
;
int multiply() {
return getA() * getB();
};
};
int main() {
Basic *basic = new Basic(2, 4);
Derived *derived = (Derived *)basic;
printf("%d * %d = %d\n", basic->getA(), basic->getB(), derived-
delete basic;
return 0;
}
</code>
lately I had a problem where I wanted to cast a basic class to a
derived type, which did not introduce any new members and did not
change any stuff with dynamically allocated memory. I just wanted to
add some methods to the class.
So my question is:
Is it valid C++ to create a basic class and to cast it to a derived
one the way I did in my example below? The example works fine for
MinGW, but I'm not sure if this is ABI dependent.
Example code:
<code>
#include <stdio.h>
class Basic {
public:
Basic(int a, int b) {
a_ = a;
b_ = b;
};
int getA() {
return a_;
};
int getB() {
return b_;
};
private:
int a_, b_;
};
class Derived : Basic {
public:
Derived(int a, int b) : Basic(a, b) {}
;
int multiply() {
return getA() * getB();
};
};
int main() {
Basic *basic = new Basic(2, 4);
Derived *derived = (Derived *)basic;
printf("%d * %d = %d\n", basic->getA(), basic->getB(), derived-
multiply());
delete basic;
return 0;
}
</code>