Introduction
A class lets you group data and actions together like a blueprint for objects.
A class lets you group data and actions together like a blueprint for objects.
class ClassName { public: // data members (variables) // member functions (methods) };
The class name should start with a capital letter by convention.
Use public: to allow access to members from outside the class.
class Car { public: int speed; void drive() { // code to drive } };
class Person { public: std::string name; int age; void greet() { std::cout << "Hello, " << name << "!" << std::endl; } };
This program defines a Dog class with name and age. It creates a Dog object, sets its name and age, then calls bark to print a message.
#include <iostream> #include <string> using namespace std; class Dog { public: string name; int age; void bark() { cout << name << " says Woof!" << endl; } }; int main() { Dog myDog; myDog.name = "Buddy"; myDog.age = 3; myDog.bark(); return 0; }
Remember to end the class definition with a semicolon ;.
By default, class members are private. Use public: to make them accessible.
A class groups data and functions into one blueprint.
Use class ClassName { ... }; to define a class.
Public members can be accessed from outside the class.
Car in C++?class followed by the class name and curly braces.class Car { }; with a semicolon at the end.start() inside a class?public: are labels followed by a colon, not keywords before functions.void start(); placed under the public: label.class Box {
public:
int length;
};
int main() {
Box b;
b.length = 10;
std::cout << b.length << std::endl;
return 0;
}Box has a public integer member length, so it can be accessed and assigned outside the class.b is created, b.length is set to 10, then printed. This will output 10.class Person {
string name;
public:
void setName(string n) {
name = n;
}
};string without including <string> header and without std:: prefix, which causes compilation error.Rectangle with private members width and height, and a public function area() that returns the area. Which is the correct class definition?private: label to restrict access.area() should be public to allow access from outside.width and height as private and area() as public with proper syntax.Pass the test and this pattern moves unknown