syntax of member function in c++
class MyClass {
public:
// Member function declaration
void memberFunction(int x, double y);
// Another member function declaration
int anotherFunction(char c);
};
// Definition of memberFunction
void MyClass::memberFunction(int x, double y) {
// Function body
// Perform operations using x and y
}
// Definition of anotherFunction
int MyClass::anotherFunction(char c) {
// Function body
// Perform operations using c
return 0; // Return an integer value
}
Explanation:
Class Declaration: The
class MyClass
declares a class namedMyClass
.Public Member Functions: Inside the class,
memberFunction
andanotherFunction
are declared as public member functions usingvoid
andint
return types respectively.Function Declaration:
void memberFunction(int x, double y);
declaresmemberFunction
with two parameters: an integerx
and a doubley
. It only declares the function without defining its actual implementation.Another Function Declaration:
int anotherFunction(char c);
declaresanotherFunction
with a single parameter of typechar
and anint
return type.Function Definitions: The actual definitions of these member functions are provided outside the class using
MyClass::memberFunction
andMyClass::anotherFunction
. Here, the functionality of each function is written.Definition of
memberFunction
: The implementation ofmemberFunction
takes two arguments (an integerx
and a doubley
) and performs operations using these parameters within the function body.Definition of
anotherFunction
: Similarly,anotherFunction
takes achar
parameterc
and performs operations inside the function body. It returns an integer value at the end.
These steps demonstrate the declaration and definition of member functions within a C++ class, showcasing their structure and implementation outside the class declaration.