Alok Kumar
Alok Kumar

Reputation: 101

Can we initialize an object with the help of constructor of another class?

Can we initialize an object with the help of constructor of another class?

class1 object = new class2();

Upvotes: 3

Views: 121

Answers (5)

Brett Okken
Brett Okken

Reputation: 6306

As long as class2 extends (or implements in case of an interface) class1 that is fine. For example, List<String> list = new ArrayList<>();

To be clear, you are creating an instance of class2 (or ArrayList from my example). It just so happens that you have declared your variable to be of type class1 (or List).

Upvotes: 3

juanchopanza
juanchopanza

Reputation: 227370

The only way for this to work in C++

class1 object1 = new class2();

would be to have an implicit conversion between class2* and class1. This can be achieved with a converting constructor:

struct class1
{
  class1(const class2*);
};

Whether this constitutes using a constructor of a class to "help" construct an object of a different one depends on what you mean by helping to construct.

If you meant

class1 object1 = class2();

then the converting constructor would need to take a class2 by value or reference. For example,

struct class1
{
  class1(const class2&);
};

There is no need for an is-a relationship between the types.

Upvotes: 2

Georgie
Georgie

Reputation: 61

Its possible only if class2 s a subclass of class1. 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..

Upvotes: 1

Fytch
Fytch

Reputation: 1087

Only speaking for C++: It's possible but the classes require a polymorphic "is a" relation (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: Meanwhile the thread opener removed the C++-Tag, so my answer doens't have any relevance anymore.

Upvotes: 1

class class1{}
class class2 extends class1{}

If you have a parent child relationship in class hierarchy then it is not a problem at all. Then class1 object1 = new class2(); is valid actually what is happening inside is you are having an class2 object but that is referenced by an class1 variable.

but if you have like

class class1{}
class class2{}

Then this is not working

Upvotes: 0

Related Questions