Welcome to your comprehensive guide on C++ Data Members! In this lesson, we'll explore the world of data members, learn their importance, and understand how to use them in your C++ programs.
Data members, also known as instance variables, are variables declared within a class that store data for each object of that class. They are essential for storing and managing the state of an object.
Data members allow us to create complex objects with multiple properties. By encapsulating these properties within a class, we can control their access and maintain the integrity of our objects.
C++ supports several basic data types, such as int, float, char, bool, etc. Here's an example of a class with basic data members:
#include <iostream>
class Person {
public:
int age;
float height;
char gender;
bool isStudent;
};
int main() {
Person person;
person.age = 25;
person.height = 1.75f;
person.gender = 'M';
person.isStudent = true;
std::cout << "Person's age: " << person.age << "\n";
std::cout << "Person's height: " << person.height << "\n";
std::cout << "Person's gender: " << person.gender << "\n";
std::cout << "Is Person a student? " << person.isStudent << "\n";
return 0;
}Data members are private by default in C++, which means they can only be accessed within the class. However, we can declare them as public to allow external access. In the example above, we declared our data members as public, enabling us to access and manipulate them in the main function.
What are the four basic data types used in the example above?
In this lesson, we learned about data members in C++, their importance, and their types. By understanding and mastering data members, you'll be able to create more complex and realistic objects for your programs.
Stay tuned for our next lesson on C++ Access Modifiers! š