Create class methods using C++

Class methods are methods or functions that belong to a specific class. For example, a Car Class can have a Drive method. In this simple tutorial, you will learn how to create methods in a class using a C++ programming language. Besides, you will learn how to access these methods from other areas in your program.

Create a Method in C++

To begin with, you must have a class created, then add a method to it:

#include <iostream>
using namespace std;
 
class Car {
public:  

// function to print a message
    void Print()
    {
        cout << "My car is a BMW\n";
    }
    
    
    // Function that takes input when it gets called, then print an output
    void PrintModel(  std::string model)
    {
        cout << "My car is a " << model << "\n";
    }
};

int main()
{
    // creating an instance of the class Car
    Car MyCar;

    // calling the first method
   MyCar.Print();
   
   // calling the second method and passing a value "Tesla"
MyCar.PrintModel("Tesla");
    return 0;
}

Now run the program, the output is below:

Output
My car is a BMW

My car is a Tesla

Happy Coding!

Leave a Reply

Your email address will not be published.