Introduction
Class attributes and methods (also known as data members and member functions) are fundamental components of classes in C++. Attributes store the state of an object, while methods define the behavior of an object. Understanding how to define and use class attributes and methods is crucial for implementing Object-Oriented Programming (OOP) principles.
Class Attributes
Class attributes (data members) are variables that hold the data associated with a class and its objects. They can be of any data type, including other classes.
Syntax for Defining Attributes
class ClassName {
public:
dataType attributeName; // Public attribute
private:
dataType attributeName; // Private attribute
protected:
dataType attributeName; // Protected attribute
};
Example: Defining and Using Class Attributes
#include <iostream>
using namespace std;
class Person {
public:
// Public attributes
string name;
int age;
// Method to display person's details
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Create an object of the Person class
Person person1;
// Initialize attributes
person1.name = "Alice";
person1.age = 25;
// Display the person's details
person1.display();
return 0;
}
Output
Name: Alice, Age: 25
Explanation
- The
Person
class has public attributesname
andage
. - The
display
method prints the values of the attributes. - The
person1
object is created and its attributes are initialized and displayed.
Class() Methods
Class methods (member functions) define the behavior of a class. They can manipulate class attributes and perform operations relevant to the class.
Syntax for Defining Methods
class ClassName {
public:
returnType methodName(parameters) {
// Method body
}
};
Example: Defining and Using Class Methods
#include <iostream>
using namespace std;
class Rectangle {
private:
// Private attributes
double length;
double width;
public:
// Method to set dimensions
void setDimensions(double l, double w) {
length = l;
width = w;
}
// Method to calculate area
double calculateArea() {
return length * width;
}
// Method to display dimensions
void displayDimensions() {
cout << "Length: " << length << ", Width: " << width << endl;
}
};
int main() {
// Create an object of the Rectangle class
Rectangle rect;
// Set dimensions
rect.setDimensions(5.0, 3.0);
// Display dimensions
rect.displayDimensions();
// Calculate and display area
cout << "Area: " << rect.calculateArea() << endl;
return 0;
}
Output
Length: 5, Width: 3
Area: 15
Explanation
- The
Rectangle
class has private attributeslength
andwidth
. - The
setDimensions
method initializes the attributes. - The
calculateArea
method returns the area of the rectangle. - The
displayDimensions
method prints the dimensions of the rectangle.
Access Specifiers
Access specifiers define the accessibility of class members. They are crucial for encapsulation, a key principle of OOP.
Types of Access Specifiers
- public: Members are accessible from outside the class.
- private: Members are accessible only within the class.
- protected: Members are accessible within the class and derived classes.
Example: Using Access Specifiers
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
// Constructor
BankAccount(double initialBalance) {
balance = initialBalance;
}
// Method to deposit money
void deposit(double amount) {
balance += amount;
}
// Method to withdraw money
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
cout << "Insufficient balance!" << endl;
}
}
// Method to display balance
void displayBalance() {
cout << "Balance:
quot; << balance << endl; } }; int main() { // Create a BankAccount object BankAccount account(1000.0); // Perform transactions account.deposit(500.0); account.withdraw(200.0); account.displayBalance(); account.withdraw(1500.0); account.displayBalance(); return 0; }
Output
Balance: $1300
Insufficient balance!
Balance: $1300
Explanation
- The
BankAccount
class has a private attributebalance
. - Public methods
deposit
,withdraw
, anddisplayBalance
provide controlled access to thebalance
attribute. - The
account
object performs transactions and displays the balance.
Constructors and Destructors
Constructors
Constructors initialize objects when they are created. They have the same name as the class and no return type.
Example: Constructor
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
// Constructor
Person(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Create an object using the constructor
Person person1("Alice", 25);
// Display the person's details
person1.display();
return 0;
}
Output
Name: Alice, Age: 25
Explanation
- The
Person
class has a constructor that initializesname
andage
. - The
person1
object is created using the constructor and its details are displayed.
Destructors
Destructors perform cleanup tasks when an object is destroyed. They have the same name as the class preceded by a tilde (~
) and no parameters.
Example: Destructor
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
// Constructor
Person(string n, int a) {
name = n;
age = a;
}
// Destructor
~Person() {
cout << "Destructor called for " << name << endl;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Create an object using the constructor
Person person1("Alice", 25);
// Display the person's details
person1.display();
return 0;
}
Output
Name: Alice, Age: 25
Destructor called for Alice
Explanation
- The
Person
class has a destructor that prints a message when called. - The destructor is automatically called when
person1
goes out of scope.
Example Programs
Example 1: Student Class with Attributes and Methods
#include <iostream>
using namespace std;
class Student {
private:
string name;
int rollNumber;
double marks;
public:
// Constructor
Student(string n, int r, double m) {
name = n;
rollNumber = r;
marks = m;
}
// Method to display student details
void display() {
cout << "Name: " << name << ", Roll Number: " << rollNumber << ", Marks: " << marks << endl;
}
};
int main() {
// Create a Student object
Student student1("John", 101, 89.5);
// Display student details
student1.display();
return 0;
}
Output
Name: John, Roll Number: 101, Marks: 89.5
Explanation
- The
Student
class has private attributesname
,rollNumber
, andmarks
. - The constructor initializes the attributes.
- The
display
method prints the student’s details.
Example 2: Book Class with Methods
#include <iostream>
using namespace std;
class Book {
private:
string title;
string author;
double price;
public:
// Constructor
Book(string t, string a, double p) {
title = t;
author = a;
price = p;
}
// Method to display book details
void display() {
cout << "Title: " << title << ", Author: " << author << ", Price:
quot; << price << endl; } // Method to apply discount void applyDiscount(double percentage) { price -= price * (percentage / 100); } }; int main() { // Create a Book object Book book1("C++ Programming", "Bjarne Stroustrup", 45.99); // Display book details book1.display(); // Apply discount and display updated details book1.applyDiscount(10); book1.display(); return 0; }
Output
Title: C++ Programming, Author: Bjarne Stroustrup, Price: $45.99
Title: C++ Programming, Author: Bjarne Stroustrup, Price: $41.391
Explanation
- The
Book
class has private attributes title, author, and price. - The constructor initializes the attributes.
- The
display
method prints the book’s details. - The
applyDiscount
method applies a discount to the price.
Conclusion
Class attributes and methods are essential components of C++ classes. Attributes store the state of an object, while methods define the behavior of an object. This chapter covered how to define and use class attributes and methods, including constructors and destructors, and the importance of access specifiers. Example programs demonstrated practical applications of these concepts. Understanding how to use class attributes and methods effectively will help you write more organized and maintainable code in C++.