954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Does an object with methods require more memory than one without?

All things equal, does an object of a class which has methods take up more memory resources than an instance of a class without methods. What if it is a vector of such objects?

For example:

class A{

public:
   void DoSomething();
   void DoSomethingelse();

private:
   int x, y;
};

class B{

private:
    int x, y;
};
Jsplinter
Junior Poster in Training
65 posts since Nov 2009
Reputation Points: 10
Solved Threads: 0
 

No.

The methods are associated with the type of the object (i.e. the class), they are not associate with the object, so they require no extra storage space on a per object basis. In fact, you can easily test it, just apply the sizeof() operator on a class with and without methods, both with the same data members. The sizes will be the same.

However, if you have virtual functions in your class, then the objects of that class will have to store a pointer to the virtual table (the virtual table is a simple per-class look-up table of function pointers for all the virtual methods). In this case (if you have one or more virtual functions), the objects will be one "pointer-size" bigger, which is usually negligible (the size of a pointer is usually the same as an "int", i.e. the natural word size of the computer, e.g. 32bits or 64bits). But in the example you showed, you have no virtual functions, so, no virtual table pointer, and thus, it doesn't make a difference.

You can try the following to see for yourself:

#include <iostream>

class A {
public:
   void DoSomething();
   void DoSomethingelse();
private:
   int x, y;
};

class B {
private:
    int x, y;
};

class C {
public:
   virtual void DoSomething();     //notice the 'virtual' here,
   virtual void DoSomethingelse(); // and here.
private:
   int x, y;
};

int main() {
  std::cout << "the size of A is " << sizeof(A) << std::endl;
  std::cout << "the size of B is " << sizeof(B) << std::endl;
  std::cout << "the size of C is " << sizeof(C) << std::endl;
  return 0;
};

On my computer it gives: 8 8 12. And that was expected!

mike_2000_17
Posting Virtuoso
Moderator
2,137 posts since Jul 2010
Reputation Points: 1,634
Solved Threads: 457
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: