Non-virtual Inheritance overhead question

I have this example question about inheritance.

Let's say I have two classes with partial common functionality.
Note that they are actually have more differences than this, the name and stuff are just basic examples.

Scenario 1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Shape {
  // stuff exactly the same in both:
  std::vector<Vertex> m_vertices;
  void send_vertices_to_GPU(Format format);

  // Unique stuff to Shape:
  void draw();
  int  num_spikes;
};
struct Curve {
  // stuff exactly the same in both:
  std::vector<Vertex> m_vertices;
  void send_vertices_to_GPU(Format format);

  // Unique stuff to Curve:
  void draw();
  int some_other_variable;
};


So let's say I combine the common functionality into a VertexObject base class,
simply to prevent repeated code.

Scenerio 2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct VertexObject {
  std::vector<Vertex> m_vertices;
  void send_vertices_to_GPU(Format format)
  {
      // ...
  }
};

struct Shape : VertexObject {
  void draw()
  {
    // draw my particular shape using m_vertices 
  }
  int shape_data;
};
struct Curve : VertexObject {
  void draw()
  {
    // draw my particular curve also using m_vertices
  }
  int curve_data;
};


Since there are no virtual member functions in any of the classes,
does Scenario 2, which saves on repeated code, have any overhead (I'm interested in both space and speed, but mostly speed) due to inheritance, or does the compiler know how to simplify the inheritance?
Last edited on
There is no difference in execution speed. The linker resolves the calls to correct entry point.

There is a space saving in the executable because the function only exists once.
Great thanks, that's what I assumed as far as speed goes, and it's even better to hear that the compiler doesn't automatically make copies for each subclass and instead saves space. =)

EDIT: Actually if someone is still here, I am correct in saying that having to now call the base class's constructor during the sub class's construction will not cause extra overhead as opposed to directly initializing the member data?
Last edited on
Topic archived. No new replies allowed.