Reputation: 3
For example we have code
class MyClass
{
private:
int data;
public:
int getData()
{
return data;
}
};
int main()
{
MyClass A, B, C;
return 0;
}
Since A, B and C are objects of MyClass
, all have their own memory.
My question is that, are all of these objects share same memory for methods of class ( getData()
in this case) or all objects have separate code segment for each object.?
Tnahks in advance....
Upvotes: 0
Views: 892
Reputation: 93534
In your example, MyClass::getData() is 'inline', so in that case the location of the instructions for each instance may well be in different locations under some circumstances.
Most compilers only truly in-line code when optimisation is enabled (and even then may choose not to do so). However, if this in-line code were defined in a header file, the compiler would necessarily generate code for each compilation unit in which the class were used, even if it were not in-lined within the compilation unit. The linker may or may not then optimise out the multiple instances of the code.
For code not defined inline all instances will generally share the same code unless the optimiser decides to inline the code; which unless the linker is very smart, will only happen when the class is instantiated and used in the same compilation unit in which it was defined.
Upvotes: 0
Reputation: 20760
In general with classes and objects the following is how it works:
A class is a description of data and operations on that data.
An object is a specification of the type of object (the class it represents) and the values of the attributes. Because the type of the object is saved the compiler will know where to find the methods that are being called on the object. So even though a new copy of the data is created when a new object is made, the methods still are fixed.
Upvotes: 0
Reputation:
The C++ Standard has nothing to say on the subject. If your architecture supports multiple code segments, then whether multiple segments are used is down to the implementation of the compiler and linker you are using. It's highly unlikely that any implementation would create separate segments for each class or object, however. Or indeed produce separate code for each object - methods belong to classes, not individual objects.
Upvotes: 2
Reputation: 8063
Same.
You could be interested in knowledge of how things in C++ are implemented under the hood.
Upvotes: 0