Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to a constructor?

Tags:

c++

I've got a class A, which consists of objects B and C. How to write a constructor of A that gets B and C objects? Should I pass them by value, by (const) reference, or a pointer? Where should I deallocate them?

I thought about pointers, because then I could write:

A a(new B(1,2,3,4,5), new C('x','y','z'))

But I don't know whether it's a good practice or not. Any suggestions?

like image 290
mik01aj Avatar asked Jul 08 '10 07:07

mik01aj


People also ask

How do you pass parameters to a constructor?

You can only define the coursebookname variable one time (which is when you specify the type). Remove the String designation from before the variable name when you pass it to the Person constructor and it should work fine. Person p1 = new Person(cousebookname); Spelling aside.

How do you pass a parameter to a constructor in C++?

Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function.

Can a constructor receive parameters?

Constructors can also take parameters, which is used to initialize attributes.

How do you add a parameter to a constructor in Java?

In case you want to pass parameters to the constructor, you include the parameters between the parentheses after the class name, like this: MyClass myClassVar = new MyClass(1975); This example passes one parameter to the MyClass constructor that takes an int as parameter.


1 Answers

Usually you pass by const reference:

A a(B(1,2,3,4,5), C('x','y','z'))

No need for pointers here.

Usually you store values unless copying is too inefficient. The class definition then reads:

class A {
private:
    B b;
    C c;
public:
    A(const B& b, const C& c): b(b), c(c) { }
};
like image 153
Philipp Avatar answered Oct 02 '22 15:10

Philipp