cpp / beginner
Snippet
Introduction to Classes and Objects
Classes are blueprints for creating objects. They bundle data (attributes) and functions (methods) together. An object is a specific instance of a class. The class defines what every Dog will have, while each Dog object has its own specific values.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>using namespace std;class Dog {public:string name;int age;void bark() {cout << name << " says: Woof!" << endl;}void birthday() {age = age + 1;}};int main() {Dog myDog;myDog.name = "Buddy";myDog.age = 3;myDog.bark();cout << "Age: " << myDog.age << endl;myDog.birthday();cout << "New Age: " << myDog.age << endl;return 0;}
Breakdown
1
class Dog {
Begins the class definition named Dog
2
public:
Members after this are accessible from outside the class
3
string name; int age;
Data members (attributes) that every Dog object will have
4
void bark()
A method that prints a barking message using the object's name
5
Dog myDog;
Creates an actual Dog object (instantiation)
6
myDog.name = "Buddy";
Accesses the name attribute using the dot operator