cpp / beginner
Snippet
Classes: Blueprints for Objects
Classes are user-defined blueprints that combine data (attributes) and functions (methods) into a single type. Objects are instances of classes. The class keyword defines the type, while objects are created from that type. Members can be public (accessible everywhere) or private.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>#include <string>class Dog {public:std::string name;int age;void bark() {std::cout << name << " says: Woof!" << std::endl;}};int main() {Dog myDog;myDog.name = "Buddy";myDog.age = 3;myDog.bark();return 0;}
Breakdown
1
class Dog { }
Defines a new class type named Dog
2
std::string name;
Member variable to store the dog's name
3
void bark()
Member function that outputs bark sound
4
Dog myDog;
Creates an object (instance) of class Dog