Lesson 2 of 8Article16 minFREE
Classes and Objects
Classes model objects with state and behavior. Use constructors for initialization and methods for operations on object state.
Class design basics
Classes model objects with state and behavior. Use constructors for initialization and methods for operations on object state.
Simple class example
#include <iostream>
#include <string>
using namespace std;
class Course {
private:
string title;
int lessons;
public:
Course(string t, int l) : title(t), lessons(l) {}
void printInfo() const {
cout << title << " has " << lessons << " lessons" << endl;
}
};Encapsulation best practices
- Keep fields private by default.
- Expose behavior with public methods.
- Mark methods const when they do not modify object state.