CMP1002 Lecture6
CMP1002 Lecture6
Erkut ARICAN
Lecture 6
const (Constant) Objects and
const Member Functions
const Objects
We utilize constant objects and constant
member functions to avoid object alterations
and enforce the concept of minimal
permission.
// Define a member function named getArea that returns the area of the Circle object
// using the formula pi * r^2, where pi is approximated as 3.14
double getArea() const {
return 3.14 * radius * radius;
}
For example, if the object is declared const, the compiler selects the
const version of the function. On the other hand, if the object is not
const, the compiler selects the non-const version of the function. This
allows for more flexible use of member functions in different contexts.
class Student {
public:
Student(const std::string& n, int a, const std::string& m);
void print() const;
private:
std::string name;
int age;
std::string major;
const int id; // const data member
static int idCount; // static data member for generating unique IDs
};
int main() {
Student s1("Alice", 20, "Computer Science");
s1.print();
return 0;
}
•Friend functions are defined outside the scope of the class they are
friends with.
class MyClassTwo;
class MyClassOne {
friend class MyClassTwo; // declare MyClassTwo as a friend class of MyClassOne
};
36
(3, 4)
Magnitude of v: 5
The type of the this pointer depends on the object's type and
whether the member function is declared const.
c1.increment();
c1.printCount(); // prints "Count: 11"
return 0;
}
Count: 10
Count: 20
Count: 11
Object address: 0x7ffee5a5a998
Object address: 0x7ffee5a5a988
We allocate dynamic memory for an object of type Time using the new
operator as new Time
The new operator initializes the object using the default constructor of Time
and returns the memory address of the object as a Time * pointer
Static data members are not global variables, as they have class
scope
59
60
65