Default constructor c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Default constructor c++

How do you perform a default constructor that has a default value of 0 to the variable of m_throttle(for example)?? Thanks

13th Mar 2019, 10:50 PM
lakas
5 Answers
+ 6
Charmaine Labastida At this point, I'm still very unsure what you need to achieve, but I've tweaked a bit of your code to hopefully create something which works according to your description. https://code.sololearn.com/chNVZLXpwxfY/?ref=app
14th Mar 2019, 8:43 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
A default constructor is a constructor called with no arguments. If you want it to initialize m_throttle to 0, then myClass() { m_throttle = 0; } or using initialization list myClass() : m_throttle(0) {}
13th Mar 2019, 11:11 PM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Well... if you're already using class member initialisation int m_throttle {0}; m_throttle is already 0 and there should be no need to explicitly set it to 0 using a setter (although you may). Your code works as long as you define your setter. void Car::setThrottle(int n) { m_throttle = n; } and should be called as: setThrottle(0); if you want to set m_throttle to 0.
14th Mar 2019, 12:38 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
i need to create a virtual method serialize(overriding the Vehicle virtual serialize) my output should be : “Car: Throttle: throttle @ [lat, lon, alt]” //lat, lon, alt are variables so far what i have is: Car.h class Car : public Vehicle { private: virtual void Serialize(ostream& os); } Car.cpp void Car::Serialize(ostream& os) { os << “Car: Throttle: throttle @ [“; //what to put inside??? } Vehicle.h class Vehicle { private: virtual void serialize(ostream& os); }
14th Mar 2019, 2:06 AM
lakas
+ 1
does this work? Car.h class Car { public: Car(); private: int m_throttle {0}; }; Car.cpp Car::Car() { cout << “Car: Default-ctor” << endl; setThrottle(m_throttle); }
13th Mar 2019, 11:27 PM
lakas