Can I initialize an object using the constructor of another class?
Can I initialize an object using the constructor of another class?
class1 object = new class2();
As long as it class2
extends (or implements in the case of an interface) class1
, that's fine. For example,List<String> list = new ArrayList<>();
To be clear, you are instantiating class2
(or ArrayList
from my example). It just so happens that you have specified your type variable class1
(or List
).
The only way to work in C ++
class1 object1 = new class2();
will have an implicit conversion between class2*
and class1
. This can be achieved with a conversion constructor:
struct class1
{
class1(const class2*);
};
Whether or not it uses the constructor of a class to "help" to create an object of another, it depends on what you mean by helping build.
If you meant
class1 object1 = class2();
then the conversion constructor must take a value class2
by value or reference. For example,
struct class1
{
class1(const class2&);
};
There is no need for an is-a relationship between types.
C ++ only: Possibly, but classes require a polymorphic "is" relationship (public inheritance in C ++). For example:
class class1 { };
class class2 : public class1
{
class2(int) {}
};
class1* object1 = new class2(42); // A pointer is needed (in C++)
delete object1;
// better would be:
std::unique_ptr<class1> object1(new class2(42));
Edit: In the meantime, the thread developer has removed the C ++ - Tag, so my answer has nothing to do with it anymore.
This is only possible if class2 is a subclass of class 1. This is called polymorphism.
class Class1{
/*
*
*
body of class1
*
*/
}
class Class2 extends Class1{
/*
*
*
body of class2
*
*/
}
Then you can declare
Class1 object1 = new Class2 ();
Hope this helped.
class class1{}
class class2 extends class1{}
If you have parent relationships with children in a class hierarchy, this is not a problem. then
class1 object1 = new class2();
what actually happens internally is you have a class2 object, but it is referenced by the class1 variable.
but if you have
class class1{}
class class2{}
Then it doesn't work