Abstract class reference

What does this mean when there is a link to an abstract class? I found it in code and I do not understand it.

I thought an abstract class could not be created. How can you give him a link?

+7
source share
4 answers

A reference to an abstract class is similar to a pointer to an abstract class: it needs to refer to an object of some non-abstract subclass of an abstract class. You can use such a link to invoke virtual methods in a reference class using syntax . , similar to a pointer to an interface in Java.

+13
source

An abstract class is for output. The Liskov substitution principle states that everything that uses the abstract parts of types that come from an abstract base should work equally well, using the base polymorphically. This means that you must use a link or a pointer to the base.

+6
source
 class Abstract { public: virtual void foo() = 0; }; class Implementation : public Abstract { public: void foo() { std::cout << "Foo!" << std::endl; } }; void call_foo(Abstract& obj) { obj.foo(); } int main() { Abstract *bar = new Implementation(); call_foo(*bar); delete bar; } 

bar is a pointer abstract class. It can be dereferenced using the * operator and passed as reference to call_foo , because this is what call_foo asks call_foo ( Abstract* asks for a pointer, whereas Abstract& asks for a link).

The above example passes a reference to an abstract class, and when foo() is called using the notation . (instead of designating a pointer -> ), it prints Foo! because this is what Implementation does.

Hope this helps.

+3
source

Links in C ++ behave (almost) like hidden pointers. In particular, the same polymorphic behavior that you can get with a pointer, you can achieve it with a link. That is, the following (almost) equivalent

 int *i = &a; int &j = a; 

Assuming a is an integer defined somewhere in the previous lines. After the appearance of the link j, it is completely equivalent to the occurrences (* i). The main difference is that the link does not give you the pain of memory management, while the pointer does (you are responsible for handling the new (s) and deleted (s)). In addition, a pointer must not point to something, while a link cannot exist if it does not refer to anything. In addition, you can assume that they behave the same.

Therefore, it is absolutely legal to have a link to an abstract object. You will often find this in signature functions, where polymorphic behavior can be achieved either through references or pointers. But links give easier syntax, for example, the following code snippet shows

 A a; A* ptr = &a; A& ref = a; ref(); ptr->operator()(); (*ptr)(); 

assuming class A overloads operator () .

+2
source

All Articles