Sunday, May 7, 2017

"A pure virtual method is called." Do you know how to do this in C++?

Hello, my dear friend!

"A pure virtual method is called". Do you know how to do this in C++?
 I'll show you this. I like GNU compiler, so I will use it.

Example #1. Simple.

Code:

#include <cstdlib>
#include <iostream>

class A {
public:
 A() {
  init();
 }

 void init(void) {
  f();
 }

 virtual void f(void) = 0;
};

class B : public A {
public:
 virtual void f(void) {
  std::cout << "f() in B" << std::endl;
 }
};

int main(void) {
 B b;
 b.f();
 
 return EXIT_SUCCESS;
}

Build and result:

bodro@bodronote:~/workspace/develop/test/pure_virtual_func$ export LC_ALL=C
bodro@bodronote:~/workspace/develop/test/pure_virtual_func$ ls -lah t1.cpp 
-rw-r--r-- 1 bodro bodro 297 May  7 13:24 t1.cpp
bodro@bodronote:~/workspace/develop/test/pure_virtual_func$ g++ -Wall -Wextra \
> -Werror -O0 -o t1.bin t1.cpp && ./t1.bin
pure virtual method called
terminate called without an active exception
Aborted
bodro@bodronote:~/workspace/develop/test/pure_virtual_func$

Example #2. I will use an assembler (AT&T).

Code:

#include <cstdlib>
#include <iostream>

class A {
public:
 A() {
  asm ("mov (%rax),%rcx");
  asm ("mov 0(%rcx),%rcx");
  asm ("call *%rcx");
 }

 virtual void f(void) = 0;
};

class B : public A {
public:
 virtual void f(void) {
  std::cout << "f() in B" << std::endl;
 }
};

int main(void) {
 B b;
 b.f();

 return EXIT_SUCCESS;
}

Build and result:

bodro@bodronote:~/workspace/develop/test/pure_virtual_func$ export LC_ALL=C
bodro@bodronote:~/workspace/develop/test/pure_virtual_func$ ls -lah t2.cpp 
-rw-r--r-- 1 bodro bodro 333 May  7 13:36 t2.cpp
bodro@bodronote:~/workspace/develop/test/pure_virtual_func$ g++ -Wall -Wextra \
> -Werror -O0 -o t2.bin t2.cpp && ./t1.bin 
pure virtual method called
terminate called without an active exception
Aborted
bodro@bodronote:~/workspace/develop/test/pure_virtual_func$

The story of how it works I'll write later.


Best regards,
Vasiliy V. Bodrov aka Bodro,
the 7-th of May, 2017 year.

No comments:

Post a Comment

How to reverse singly linked list in C (trivial way)

There is a beautiful morning. It's snowing. And I decided to write one more article. Today it will be just simple article where I would...