How to Create Class in C++: Syntax and Example
In C++, you create a class using the
class keyword followed by the class name and curly braces containing members. Members can be variables and functions that define the class behavior. Use public: to make members accessible outside the class.Syntax
A class in C++ is defined using the class keyword, followed by the class name and a pair of curly braces { }. Inside, you declare variables (called data members) and functions (called member functions). Access specifiers like public: control which members are accessible from outside the class.
- class: keyword to define a class
- ClassName: the name you give your class
- public: members accessible from outside
- private: members accessible only inside the class (default)
- data members: variables that hold data
- member functions: functions that operate on data
cpp
class ClassName { public: // public members private: // private members };
Example
This example shows how to create a simple Car class with a public data member and a member function to display its value.
cpp
#include <iostream> using namespace std; class Car { public: string brand; void showBrand() { cout << "Car brand: " << brand << endl; } }; int main() { Car myCar; myCar.brand = "Toyota"; myCar.showBrand(); return 0; }
Output
Car brand: Toyota
Common Pitfalls
Beginners often forget to add a semicolon ; after the class definition, which causes a compilation error. Another common mistake is not specifying public: before members, making them private by default and inaccessible outside the class.
Also, trying to access private members directly from outside the class will cause errors.
cpp
/* Wrong: Missing semicolon after class */ class Person { public: string name; }; // <-- added missing semicolon here /* Wrong: Members are private by default */ class Person { string name; // private by default }; int main() { Person p; // p.name = "Alice"; // Error: 'name' is private } /* Right: Add semicolon and public access */ class Person { public: string name; }; int main() { Person p; p.name = "Alice"; // Works fine }
Quick Reference
- Use
class ClassName { ... };to define a class. - Members are
privateby default; usepublic:to expose them. - Always end class definition with a semicolon
;. - Access members with dot
.operator on objects. - Use member functions to interact with private data safely.
Key Takeaways
Define a class with the
class keyword followed by its name and curly braces.Members are private by default; use
public: to make them accessible outside.Always end your class definition with a semicolon
; to avoid errors.Use objects and the dot operator to access public members and functions.
Member functions help safely access or modify private data inside the class.