MOCKSTACKS
EN
Questions And Answers

More Tutorials








C++ Class Constructor

In C++, A constructor is a special method that is automatically called when an object of that class is created.

The constructor function has the same name of Class followed by parenthesis.

C++ Example of Class with constructor

In the below example you will see we created a public function called: Vehicle() which is the same as the class name, in this function we are writing to output a message: New vehicle object!

When we defined the Vehicle newVehicle; it will run the code within the constructor and print to output.

#include <iostream>
#include <string>

using namespace std;

class Vehicle {
  public:	
    Vehicle() {     
          cout << "New vehicle object!" << "\n";
    }
 public:              
    string color;        
    string make;         
    string model;
 public:             
    string getColorAsMessage() { 
      return "My color is: " + color;
    }
};



int main() {

  // Vehicle section
  Vehicle newVehicle;  
  newVehicle.color = "Red";
  newVehicle.make = "BMW";
  newVehicle.model = "X5";
  cout << newVehicle.getColorAsMessage() << "\n"; 
  cout << newVehicle.make << "\n"; 

  return 0;
}

Output

New vehicle object!
My color is: Red
BMW

Conclusion

In this page (written and validated by ) you learned about C++ Class Constructor . What's Next? If you are interested in completing Cpp tutorial, your next topic will be learning about: Cpp Destructor.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.