Mark As Completed Discussion

Classes and Objects

In C++, classes and objects are the building blocks of object-oriented programming (OOP). A class is a blueprint for creating objects, and an object is an instance of a class.

Basketball Player Class Example

To understand the concept of classes and objects, let's consider an example related to basketball. We'll create a BasketballPlayer class that represents a basketball player. The class will have attributes like name, team, age, and height. It will also have a method to print the player's information.

Here's an example of a BasketballPlayer class:

TEXT/X-C++SRC
1// Class definition
2// BasketballPlayer class to represent a basketball player
3class BasketballPlayer {
4public:
5    string name;
6    string team;
7    int age;
8	double height;
9
10    // Constructor
11    BasketballPlayer(string n, string t, int a, double h) {
12        name = n;
13        team = t;
14        age = a;
15        height = h;
16    }
17
18    // Method to print player information
19    void printInfo() {
20        cout << "Player Name: " << name << endl;
21        cout << "Team: " << team << endl;
22        cout << "Age: " << age << endl;
23        cout << "Height: " << height << " inches" << endl;
24    }
25};
26
27int main() {
28    // Create a BasketballPlayer object
29    BasketballPlayer player("Kobe Bryant", "Los Angeles Lakers", 41, 78.0);
30
31    // Call the printInfo method
32    player.printInfo();
33
34    return 0;
35}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment