0

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;
};
2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by mike_2000_17
1

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!

Edited by mike_2000_17: n/a

Votes + Comments
wow, thank you for that great answer!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.