How to create a class in cpp?
#include<iostream> using namespace std; class myclass{ public: int name(int a,int b); //this is function }; int myclass::name(int a,int b) //This is a member function { if(a>b){ cout <<a; } else { cout<<b; } return 0; } int main() { myclass obj; // myclass object is obj obj.name(30,50); //a=30,b=50 }
In the myclass
declaration, the member function name
is declared to take two integer parameters a
and b
and return an integer. The function is not defined within the class declaration, but its definition is provided later in the code.
The definition of the name
function begins with int myclass::name(int a, int b)
, indicating that it is a member function of the myclass
class. Inside the function, there is an if
statement that checks if a
is greater than b
. If this condition is true, it prints the value of a
using cout
. Otherwise, it prints the value of b
.
The main
function is where the program starts executing. It creates an object of the myclass
class called obj
. Then, it calls the name
function on the obj
object, passing the values 30 and 50 as arguments. This will invoke the name
function, and depending on the values of a
and b
, it will print either 30 or 50 to the console.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?