Attributes of the Class
Class is like a container for two primary elements: attributes and methods. In this chapter we will learn about attributes and how to use them. For a student class common attributes will be name, gpa, email etc.
Understanding Attributes
Attributes, also often referred as properties or fields, they are the variables that are held within a class. Their job is to represent the state or qualities of objects created from the class.
Public attributes and methods in a class can be directly accessed using the dot operator (.
) on an object of the class.
main
99
1
2
3
4
5
6
7
8
9
10
class Example {
public:
float attribute;
};
int main()
{
Example obj;
obj.attribute = 25;
}
12345678910class Example { public: float attribute; }; int main() { Example obj; obj.attribute = 25; }
Note
Don't be bothered about public keyword. It will be explained later.
Task
Swipe to start coding
- Add two more attributes to a student class.
- Create an object of the class.
- Assigned values to the attributes of created instance.
Solution
solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
class Student {
public:
std::string name;
float gpa;
std::string email;
};
int main()
{
Student student;
student.name = "Bob Wise";
student.gpa = 4.0;
student.email = "great_bob@gmail.com";
}
Everything was clear?
Thanks for your feedback!
Section 1. Chapter 4
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
class Student {
public:
___ ___;
___ ___;
std::string email;
};
int main()
{
___ student;
___.___ = ___;
___.___ = ___;
student.email = "great_bob@gmail.com";
}
Ask AI
Ask anything or try one of the suggested questions to begin our chat