+ 2

Declaring object in C++ with = operator?

When constor has only one parameter, for example integer, you can create object like this: Car car= 24; But if constructor has more parameters for example 2 integers, can you call that constructor with assigment operator, or only like this: Car car(25,56);

6th Jan 2024, 4:33 PM
Adilx01
2 Antworten
+ 5
Nice one! If your constructor has 2 parameters, then it is not scalar. So you can use the assignment operator, but you should be careful to use a 2D value: Car car = {12,24};
6th Jan 2024, 10:21 PM
🇮🇱 Radin Masiha 🇮🇱
🇮🇱 Radin Masiha 🇮🇱 - avatar
+ 1
In C++, when a constructor has more than one parameter, you can't use the assignment operator (`=`) for object creation directly as you did with a single parameter. Instead, you need to use the constructor syntax with parentheses to initialize the object with multiple parameters. For example, if you have a `Car` class with a constructor that takes two integers: ```cpp class Car { public: Car(int param1, int param2) { // Constructor logic here... } }; ``` You would create an object of this class with two integers using the following syntax: ```cpp Car car(25, 56); ``` This is the standard way to initialize an object with multiple parameters in C++. The assignment operator (`=`) is used for assignment after the object has been created, not during its creation with parameters.
8th Jan 2024, 2:27 AM
𝐀𝐲𝐞𝐬𝐡𝐚 𝐍𝐨𝐨𝐫
𝐀𝐲𝐞𝐬𝐡𝐚 𝐍𝐨𝐨𝐫 - avatar