Abstract Class

I am confused, I hope somebody can clarify this for me - Thank You in advance.

ABSTRACT CLASS :
Let's assume I have a BASE ABSTRACT CLASS and two DERIVED CLASSES.
My BASE has a variable STRING NAME;

My DERIVED CLASSES have a variable STRING NAME.

When I set a value to my DERIVED CLASS variable - is that a separate variable?
I was thinking, I am just Defining the one variable in the base class accessed by the derived class,
but now I am thinking I am creating a whole separate variable in another class.

My Head Hurts :: I am confused !!
Last edited on
Yes, they are distinct variables. Consider a basic example:

1
2
3
4
5
6
7
8
9
struct A
{
  int x;
};

strut B: public A
{
  int x;
};

B inherits an x from A.
But then B also declares a variable named x.

B’s x hides A’s x. If you want to access A’s x, you must do so by explicitly asking for A’s x: A::x.

Hope this helps.

[edit]
Here’s something you can play with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

struct A
{
  int x;

  virtual void print() const
  { 
    std::cout << "A: " << x << "\n";
  }
};

struct B: public A
{
  int x;

  virtual void print() const
  {
    std::cout << "B: " << x << "\n";
    A::print();
  }
};

int main()
{
  std::cout << "size of A = " << sizeof( A ) << "\n";
  std::cout << "size of B = " << sizeof( B ) << "\n";

  B b;
  b.x    = -7;
  b.A::x = 12;

  b.print();
}


[edit 2]
Sorry, one more thing. Neither A nor B above are abstract.

An abstract class is one that cannot* be instantiated (created as an actual object using actual memory) because some of its declared methods do not have defined bodies.

*should not

As always, things get a little murkier under the water, but this should do for now.

Hope this helps.
Last edited on
Your latter hunch is right, it is making two variables.

+----------------------+
|                      |
|    DERIVED           |
|    string name       |
|   +--------------+   |
|   |              |   |
|   |  BASE        |   |
|   | string name  |   |
|   |              |   |
|   +--------------+   |
|                      |
|                      |
+----------------------+


Every DERIVED contains a BASE.

This is known as "shadowing" a variable.

If you just do my_derived_object.name, you will access the derived string, and the base string will be untouched.
Last edited on
Topic archived. No new replies allowed.