What is the structure of a class implementation in C++?
Structure of a C++ Class
A class is user-defined datatype which has data members and member functions. In C++, classes are divided into the following three sections:
1. Class Declaration Section
2. Member Function Section
3. Main Function Section
class Animal{
string animalName;
public:
Animal(string name);
void animalSound();
void printName();
};
Member Function Section
- Member functions are methods used to access data members of the class.
- Definition of member functions can be inside the class or outside the class.
- This section contains definition of the member functions that are declared inside the class.
int main(){
Animal a("Dog");
a.printName();
a.animalSound();
}
Class Declaration Section
- You can declare class using the keyword
class - You can add data members and member functions inside the class.
- Accessing the data members and member functions depends solely on the access modifiers, i.e., public, private or protected.
- A class always starts with
{and ends with};
void Animal ::
Animal(string name){
animalName = name;
}
void Animal :: animalSound(){
cout << "Woof Woof!" << endl;
}
void Animal :: printName(){
cout << animalName << endl;
}
Main Function Section
- Execution of the code starts from
main. - In this section, we can create an object of a class.
- We can call the functions defined inside the class.
#include <iostream> // Header filesusing namespace std;class Animal{ // class namestring animalName; // class data memberpublic:Animal(string name); // Animal constructorvoid animalSound(); // Member function declarationvoid printName();};Animal :: Animal(string name){ // function defintionanimalName = name;}void Animal :: animalSound(){cout << "Woof Woof!" << endl;}void Animal :: printName(){cout << animalName << endl;}int main(){Animal a("Dog"); // creating object of class Animala.printName(); // calling member functiona.animalSound(); // calling member function}
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved