0
What does ' B*p = new C ' mean?
class A { public: void f() {cout << "A";} }; class B { public: void f() {cout << "B";} }; class C { public: void f() {cout << "C";} }; int main(){ B*p = new C; // what does the ' new C ' mean? p->f(); }
4 odpowiedzi
+ 1
`new` operator manages pointer types created in heap memory.
But that code won't run because class C is not related to class B. class C should extend class B in order to achieve that.
0
By default, "new C" means: create an instance of class C and return its pointer in memory.
In fact:
auto p = new C;
p->f();
will print "C"
But you are telling that p must be a pointer to an instance of class B, not C.
As you wrote it, "B *p = new C();" the compiler will give an error: you cannot interchange pointers to different classes.
But if you insist, and use the cast operator, it will work 😉
B *p = (B *)new C;
or
auto p = (B *)new C;
in this case
p->f()
will print "B" !