In C++, you define member functions and data members within the body of a class. Here's an example demonstrating how to define both member functions and data members:
//cpp
#include <iostream>
#include <string>
// Class declaration
class Student {
private: // Access specifier
// Data members (member variables)
string name;
int age;
double gpa;
public: // Access specifier
// Member functions (methods)
// Constructor - initializes data members
Student(string n, int a, double g) : name(n), age(a), gpa(g) {}
// Setter functions - modify data members
void setName(string n) {
name = n;
}
void setAge(int a) {
age = a;
}
void setGPA(double g) {
gpa = g;
}
// Getter functions - access data members
string getName() const {
return name;
}
int getAge() const {
return age;
}
double getGPA() const {
return gpa;
}
// Member function to display student information
void displayInfo() const {
cout << "Name: " << name << ", Age: " << age << ", GPA: " << gpa << endl;
}
};
int main() {
// Creating an object of the class and initializing it using the constructor
Student student1("Alice", 20, 3.75);
// Accessing data members and calling member functions
student1.displayInfo();
// Modifying data members using setter functions
student1.setAge(21);
student1.setGPA(3.9);
// Accessing modified data members using getter functions
cout << "Updated Age: " << student1.getAge() << ", Updated GPA: " << student1.getGPA() << endl;
return 0;
}
In this example:
- The `Student` class has private data members (`name`, `age`, `gpa`) and public member functions (`setName`, `setAge`, `setGPA`, `getName`, `getAge`, `getGPA`, `displayInfo`).
- The constructor `Student(string n, int a, double g)` initializes the data members when an object is created.
- Setter functions (`setName`, `setAge`, `setGPA`) modify the values of data members.
- Getter functions (`getName`, `getAge`, `getGPA`) retrieve the values of data members.
- The `displayInfo` member function prints the student information.
This class helps in encapsulating data and behavior within a class, providing a way to manage and manipulate objects of that class.
Comments
Post a Comment