Define Class with Private Data Members
A class in C++ is a blueprint for creating objects. It defines a set of properties (data members) and methods (member functions) that the objects created from the class will have. Classes help in organizing code and implementing object-oriented programming principles such as encapsulation, inheritance, and polymorphism.
The basic syntax for defining a class in C++ is as follows:
class ClassName {
private:
// Private data members
int dataMember1;
std::string dataMember2;
public:
// Public member functions
void memberFunction1();
int memberFunction2();
};
There are three access specifiers in C++ that control the visibility and accessibility of class members:
private
: Members declared as private are accessible only within the class.
public
: Members declared as public are accessible from outside the class.
protected
: Members declared as protected are accessible within the class and by derived class instances.
In this step, you'll learn how to define a class with private data members in C++. Private data members are an essential concept in object-oriented programming that helps encapsulate and protect the internal state of an object.
First, open the WebIDE and navigate to the ~/project
directory. Create a new file called student.cpp
:
touch ~/project/student.cpp
Open the student.cpp
file in the WebIDE and add the following code to define a Student
class with private data members:
#include <iostream>
#include <string>
class Student {
private:
// Private data members
std::string name;
int age;
double gpa;
public:
// We'll add methods to interact with these private members in later steps
void displayInfo() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "GPA: " << gpa << std::endl;
}
};
int main() {
Student student;
// Note: We can't directly access private members
// student.name = "John"; // This would cause a compilation error
student.displayInfo();
return 0;
}
Let's break down the key concepts:
-
Private Data Members:
- Declared using the
private:
access specifier
- Cannot be directly accessed from outside the class
- Provide data protection and encapsulation
-
Data Types:
std::string name
: Stores student's name
int age
: Stores student's age
double gpa
: Stores student's grade point average
-
Encapsulation:
- Private members can only be accessed through public methods
- Prevents direct modification of internal data
Compile the program:
g++ student.cpp -o student
./student
Example output when running the program:
Name:
Age: 0
GPA: 0
Key points:
- Private members are hidden from outside access
- They can only be modified through class methods
- This helps maintain data integrity and control