1

[edited for C++]I am not sure when I should create class directly or using parent to init. Example :

class A : class B

USING :

1)
A* a = new A();

2)
B* a = new A();

Because of project 's requirement, I have to use number 2 . But I wonder what is better for performance ???
And if the performance of number 2 is bad, I will consider to using number 1 with a longer code :(

I think this is a good answer :
Virtual functions and performance - C++

Community
  • 1
  • 1
quanrock
  • 89
  • 2
  • 10
  • You want to talk about mechanisms of two different languages at once? – LogicStuff Dec 12 '15 at 13:16
  • Hi LogicStuff, I write both code C++ and Java for windows and android. So I have to write 2 languages depend on that idea. – quanrock Dec 12 '15 at 13:23
  • Please pick a language. C++ is not Java. Just because there is a keyword `new` in both languages doesn't mean one is the same as the other. – PaulMcKenzie Dec 12 '15 at 13:24
  • The code is not valid C++. The `new` in C++ returns a pointer, not an object. Also, post what `A` and `B` are. If there is hardly a difference, and if for some reason, constructing a `B` does something ridiculously slow, there isn't going to be any difference that you would notice if you used `new B`. Also, you write code that is understandable first. – PaulMcKenzie Dec 12 '15 at 13:31

1 Answers1

2

Number 2 harnesses the power of polymorphism. It gives you the ability to instantiate objects & assign them to a super-class reference type.

This way if you have a third class C that inherits from the abstract class A, you could do such thing as:

class B : A
class C : A

A* bObj = new B();
A* cObj = new C();

For performance comparisons, check this link: C++

Community
  • 1
  • 1
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
  • I want to know that what is better for performance. I think when we use number 2, there are 2 memory space created for instance of A and B. But If we init by using A a = new A(); => just instance of A is created. Because of project 's requirement, I have to use number 2 ! – quanrock Dec 12 '15 at 13:20
  • That 's nice,Sparta !! – quanrock Dec 12 '15 at 13:30