What does ' B*p = new C ' mean? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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(); }

28th Jul 2020, 6:03 AM
Solus
Solus - avatar
3 Answers
+ 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.
28th Jul 2020, 6:15 AM
Ipang
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" !
28th Jul 2020, 6:38 AM
Bilbo Baggins
Bilbo Baggins - avatar
28th Jul 2020, 10:08 AM
Bilbo Baggins
Bilbo Baggins - avatar