Answer to Question #150598 in C++ for Naveed munir

Question #150598

If three objects of a class are defined, how many copies of that class’s data items are stored in memory? How many copies of its member functions? Explain with the help of a valid example by writing code and depict it via diagrams where appropriate


1
Expert's answer
2020-12-13T22:51:15-0500

 Аor every object created of that class required separate copy of data member of that class.

And for member ship function there is only one copy is stored in memory.

For example :


#include <iostream>
using namespace std;
class sqaure
{
   public:
   int l;
   int getPeri();
};
// member function getPeri
int sqaure :: getPeri()
{
   return 4*l;
}
int main()
{
   sqaure s1,s2;
   s1.l=3;
   s2.l=4;
   cout<<s1.getPeri()<<endl;
   cout<<s2.getPeri()<<endl;
   return 0;
}


There is a two copy of variable or data member of the square class(int l) is created 1 for s1 and second for s2. And only one copy of the member function getPeri() is created in memory as shown in below.

S2:

   Int l=4

S1:

Int l=3

Square:

    Int getPeri()

Why only one copy of member function is created??

In c++ for member function and static variable compiler create only one copy. But member function which is not static required separate copy for each object. And it will be shared by the all the object or instance of that class.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog