Page 253 - DCAP404 _Object Oriented Programming
P. 253
Object-oriented Programming
Notes When a number of objects are created from the same class each object’s data members are created
as separate copies. However, only a single copy of methods is retained in the memory. That is all
objects of a class share a single copy of the compiled class functions. A particular object is
referenced by “this” pointer internally.
Task What do you think the disadvantages of this pointer?
Consider the following code snippet
class student
{
int marks;
public:
void setMarks(int a)
{
marks = a;
}
int main()
{
student vibhor, prashant;
vibhor.setMarks(86);
prashant.setMarks(67);
}
When the code is executed, two marks variables are created - one for vibhor and one for prashant,
but only one copy of setMarks function is kept in the memory (see the figure below).
memory
vibhor
marks
prashant
marks
SetMarks(int a)
{ marks=a }
Both the objects can execute the setMarks function. That is both the function calls given below
will work correctly.
vibhor.setMarks(86);
prashant.setMarks(67);
How is this possible? What happens is that at the compile time the compiler inserts the necessary
code into the function setMarks so that it receives the ’this’ pointer in addition to an int value as
argument as shown below.
246 LOVELY PROFESSIONAL UNIVERSITY