A class defines a blueprint for creating objects. It combines data (attributes) and fnuctions (methods) that operate on that data.
class ClassName {
public:
int memberVariable;
void memberFunction() {
std::cout << "Function called." << std::endl;
}
};
Default Access: class vs. struct
The primary distinction between class and struct in C++ is their default member access.
- Members of a
classareprivateby default. - Members of a
structarepublicby default.
#include <iostream>
class ExampleClass {
int hiddenData = 5; // private by default
};
struct ExampleStruct {
int visibleData = 5; // public by default
};
int main() {
ExampleClass objA;
// objA.hiddenData = 10; // Error: private member
ExampleStruct objB;
objB.visibleData = 20; // Allowed: public member
std::cout << "Value: " << objB.visibleData << std::endl;
return 0;
}
Member Access Specifiers
C++ provides three access specifiers to control visibility:
public: Accessible from any where (inside the class, outside, and in derived classes).protected: Accessible within the class and by derived classes, but not from outside.private: Accessible only within the class itself, not from outside or derived classes.
#include <iostream>
#include <string>
class Household {
public:
std::string address;
void displayInfo() {
address = "123 Main St";
vehicle = "Sedan";
savings = 10000;
std::cout << address << ", " << vehicle << ", " << savings << std::endl;
}
protected:
std::string vehicle;
private:
int savings;
};
int main() {
Household home;
home.address = "456 Oak Ave"; // Allowed: public
home.displayInfo();
// home.vehicle = "Truck"; // Error: protected
// home.savings = 20000; // Error: private
return 0;
}
Attributes and Methods
Attributes (member variables) store state, while methods (member functions) define behavior. Methods are often used to manipulate attributes.
#include <iostream>
#include <string>
class StudentRecord {
public:
std::string studentName;
int studentID;
void assignName(std::string name) {
studentName = name;
}
void assignID(int id) {
studentID = id;
}
void printDetails() {
std::cout << "Name: " << studentName << ", ID: " << studentID << std::endl;
}
};
int main() {
StudentRecord pupil;
pupil.assignName("Alex");
pupil.assignID(101);
pupil.printDetails();
return 0;
}
Encapsulation via Private Members
Encapsulation is achieved by making attributes private and providing public getter and setter methods to control acces. This allows for validation and hides implementation details.
#include <iostream>
#include <string>
class Person {
private:
std::string fullName;
int yearsOld;
std::string partnerName;
public:
void setName(std::string name) {
fullName = name;
}
std::string getName() {
return fullName;
}
void setAge(int age) {
if (age < 0 || age > 150) {
std::cout << "Invalid age entered." << std::endl;
yearsOld = 0;
return;
}
yearsOld = age;
}
int getAge() {
return yearsOld;
}
void setPartner(std::string partner) {
partnerName = partner;
}
};
int main() {
Person individual;
individual.setName("Jordan");
std::cout << "Name: " << individual.getName() << std::endl;
individual.setAge(30);
std::cout << "Age: " << individual.getAge() << std::endl;
individual.setPartner("Casey");
return 0;
}
Practical Example: Cube Class
This example demonstrates a class with private attributes, public methods for calculation, and two approaches to compare objects.
#include <iostream>
class Cube {
private:
int length;
int width;
int height;
public:
void setDimensions(int len, int wid, int hgt) {
length = len;
width = wid;
height = hgt;
}
int calculateSurfaceArea() {
return 2 * (length * width + length * height + width * height);
}
int calculateVolume() {
return length * width * height;
}
bool isIdenticalTo(Cube &otherCube) {
return (length == otherCube.length &&
width == otherCube.width &&
height == otherCube.height);
}
// Friend function declaration for external comparison (alternative)
friend bool compareCubes(Cube &c1, Cube &c2);
};
// Global function to compare two Cube objects
bool compareCubes(Cube &cubeOne, Cube &cubeTwo) {
return (cubeOne.calculateVolume() == cubeTwo.calculateVolume());
}
int main() {
Cube firstCube, secondCube;
firstCube.setDimensions(5, 5, 5);
secondCube.setDimensions(5, 5, 5);
std::cout << "Surface Area: " << firstCube.calculateSurfaceArea() << std::endl;
std::cout << "Volume: " << firstCube.calculateVolume() << std::endl;
// Comparison using member function
if (firstCube.isIdenticalTo(secondCube)) {
std::cout << "Cubes are identical (member function)." << std::endl;
}
// Comparison using global function
if (compareCubes(firstCube, secondCube)) {
std::cout << "Cubes have equal volume (global function)." << std::endl;
}
return 0;
}