Classes and Objects in C++
Fundamental Concepts
A class is a blueprint that defines the characteristics and behaviors of objects. It represents an abstract concept that encapsulates data and functionality.
An object is a concrete instance created from a class definition. Objects possess the properties and capabilities defined by their class.
Class Components
Classes consist of two primary components:
- Attributes (member variables/data members): These represent the data characteristics of objects, typically described as nouns (e.g., height, type, model).
- Methods (member functions): These define the actions objects can perform, usually expressed as verbs (e.g., learn, calculate, display).
Consider a "SmartDevice" class example with the following specificatinos:
Attributes: manufacturer, device_type, battery_capacity
Methods: play_media(), execute_app(), connect_network()
#include <iostream>
#include <string>
using namespace std;
class SmartDevice {
public:
string manufacturer;
string device_type;
int battery_capacity;
void play_media() {
cout << "Playing media content" << endl;
}
void execute_app() {
cout << "Executing application" << endl;
}
void connect_network() {
cout << "Establishing network connection" << endl;
}
};
Object Instantiation
Objects can be created in two ways:
- Stack allocation: Objects created on the stack have automatic storage duration and are destroyed when they go out of scope.
int main() {
// Create stack-allocated object
SmartDevice my_device;
// Set attribute values
my_device.manufacturer = "TechCorp";
my_device.device_type = "Tablet";
my_device.battery_capacity = 5000;
// Access attribute values
cout << my_device.manufacturer << endl;
cout << my_device.device_type << endl;
cout << my_device.battery_capacity << endl;
// Invoke member functions
my_device.connect_network();
my_device.play_media();
my_device.execute_app();
return 0;
}