C++ Class Definition šŸŽÆ

beginner
14 min

C++ Class Definition šŸŽÆ

Welcome to our deep dive into C++ Class Definition! In this comprehensive guide, we'll explore the fascinating world of Object-Oriented Programming (OOP) in C++, starting from the basics and moving forward to advanced examples. By the end of this lesson, you'll have a solid understanding of classes, their properties, and methods. Let's get started!

What is a Class? šŸ“

In C++, a class is a user-defined data type that encapsulates data (variables) and functions (methods) into a single entity. Think of a class as a blueprint for creating objects, similar to how a car blueprint defines the structure and functionality of a real car.

Understanding Class Members šŸ’”

A class is composed of two main components:

  1. Data Members (Variables): These are variables declared within a class, which hold the state of an object.
  2. Member Functions (Methods): These are functions declared within a class, which define the behavior of an object.

Defining a Simple Class šŸŽØ

Let's create a simple class example called Person:

cpp
#include <iostream> using namespace std; // Define the Person class class Person { public: // Data Members string name; int age; // Member Functions void introduce() { cout << "Hi, I'm " << name << " and I'm " << age << " years old." << endl; } }; // Main function int main() { // Create a Person object Person person; // Set data members person.name = "John Doe"; person.age = 25; // Call member function person.introduce(); return 0; }

In the above example, we defined a Person class with two data members (name and age) and a member function (introduce()). We then created a Person object called person and set its data members, before calling the introduce() function to display the person's information.

Access Modifiers šŸ“

In C++, access modifiers are used to control the visibility of class members. The three access modifiers are:

  1. Public: Visible and accessible everywhere, including outside the class.
  2. Private: Visible only within the class and not accessible outside the class.
  3. Protected: Visible within the class and derived classes, but not accessible outside the class.

Class Quiz šŸ’”

Quick Quiz
Question 1 of 1

What is the purpose of a class in C++?

Stay tuned for our next lesson, where we'll dive deeper into C++ classes and explore more advanced concepts! šŸš€