Declare abstract class in c++ - c++

How do i declare abstract class?
For example, I know it's using the keyword virtual like:
class test{
public:
virtual void test()=0;
}
My question is can I abstract test class like this? If not why and how
virtual class test{
}

In most cases, your abstract class contains abstract ("pure virtual" in C++ terms) methods:
class Foo {
public:
virtual ~Foo() = default;
virtual void bar() = 0;
};
That is sufficient to make it an abstract class:
Foo foo; // gcc says: cannot declare variable 'foo' to be of abstract type 'Foo'
Note that you really want to declare the destructor as virtual in your base class, or you risk undefined behavior when destroying your derived object through a base class pointer.
There also might be cases when you have no abstract methods, but still want to mark your class as abstract. There are two ways:
a. Declare your base destructor as pure virtual:
class Foo {
public:
virtual ~Foo() = 0;
virtual void bar() { }
};
Foo::~Foo() = default; // need to define or linker error occurs
b. Declare all your base constructors as protected:
class Foo {
public:
virtual ~Foo() = default;
virtual void bar() { }
protected:
Foo() = default;
};

My question is can I abstract test class like this?
No, you can't. An abstract class by definition is a class that contains at least one pure virtual function.

Your code:
class test
{
virtual void test()=0;
}
creates an abstract class.
it contains one or more pure virtual functions:
virtual void test()=0;//is a pure virtual function/method
An abstract class is a class definition that contains one or more pure virtual functions.
You can't create instances of an abstract class because it is not a complete definition.
Your code:
virtual class test
{
}
is nonsensical, does not rise to the definition of an abstract class because it does not contain one or more pure virtual function, and is an improper use of the 'virtual' keyword...
You may be confused by talk about "Virtual Base Classes" which is a misleading way of referring to the semantic of the "Abstract Class".
purpose for making an abstract class is to inherit it into derived class and there provide a full definition for the pure virtual function/s.
Abstract class could contain many fully defined methods but only one pure virtual method which would make it abstract. The simplistic example is misleading. Abstract classes are common and are often a "fix" for issues arising from the (Barbara) Liskov Substitution Principle.
Dr t

Related

Methodless Abstract class?

class Base
{
virtual void bePolymorphic() = 0; // Will never be used
};
class Derived : Base
{
virtual void bePolymorphic() override {}; // I have to do this in every derived class
};
This is the hack that I have been using recently to make Base an abstract class if it doesn't have any member functions.
In Java there is an abstract keyword. Why isn't there one in C++? Is there another way of making a class abstract?
The classic work-around to this problem* is to make destructor pure virtual. Of course you must implement it outside the class:
// In the header file
class Base {
virtual ~Base() = 0;
};
// In the source file
Base::~Base() {
}
* This suggestion comes from one of Scott Meyers' books.
No. There is no abstract specifier in C++. The equivalent is to make your constructor protected:
class Base
{
protected:
Base() {}
virtual ~Base() {}
}
In addition, the C++ equivalent of a Java interface is one in which all of your methods are pure virtual, as you have, and the constructor is protected.
Also note that it's a good idea to always make the destructor virtual in a base class. If a derived class needs a destructor and the parent's destructor isn't virtual, the derived's constructor won't be called.

Can an abstract class be implemented without pure virtual functions in C++?

I thought of using protected constructor, but it couldn't completely solve the purpose since the class inheriting from it would be able to instantiate the base class.
As for private constructor, the derived classes too would not be instantiated.
So, any suitable technique would be appreciated.
It is unclear what you are really asking for. So let me try to clear some points:
Pure virtual functions can have definitions
If your concern is that you want to provide definitions for all of the virtual functions in your base you can provide the definitions for the pure virtual functions, and they will be available for static dispatch.
Protected grants access to your base subobject, not to every instance of base
There is a common misconception that protected allows a particular derived type accessing any instance of base. That is not true. The keyword protected grants access to the base subobject within the derived type.
class base {
protected: base() {}
};
class derived : public base {
derived() : base() { // fine our subobject
base b; // error, `b` is not your subobject
}
};
The definition of an abstract class is one that has at least one pure virtual function (virtual function-signature = 0; You can't create an abstract class without them.
Can an abstract class be implemented without pure virtual functions in C++?
If you choose the point of view from Static Polymorphism, you can do that!
An abstract base class would be simply missing a default method implementation for an interface method from the deriving class.
Additionally you can use protected constructors for those CRTP base class templates, to require inheritance for instantiation.
UPDATE:
I found a nice slide show, that explains static vs dynamic polymorphism comprehensively. Each technique has it's pros and cons and certain fields of usage, additionally you can mix both techniques (wisely of course).
To elaborate a bit, I'll give a sample:
template<class Derived>
class AbstractBase
{
public:
// Equivalent for a pure virtual function
void foo()
{
// static_cast<> enforces an 'Is a' relation from Derived to AbstractBase
static_cast<Derived*>(this)->fooImpl();
}
// Equivalent for simple virtual function (overidable from Derived)
void bar()
{
static_cast<Derived*>(this)->barImpl();
}
// Default implementation for any call to bar()
void barImpl()
{
}
protected:
AbstractBase() {}
};
// Compilation will fail, since ConcreteClass1 doesn't provide
// a declaration for fooImpl()
class ConcreteClass1
: public AbstractBase<ConcreteClass1>
{
}
// Compiles fine
class ConcreteClass2
: public AbstractBase<ConcreteClass2>
{
public:
void fooImpl()
{
// Concrete implementation ...
}
}
The following sample shows that the pattern introduced above enforces an 'Is a' relationship between abstract class and inheriting class (the template parameter)
class ConcreteClass3
{
public:
void fooImpl()
{
// Concrete implementation ...
}
}
// Instantiation will fail, because
// * the constructor is protected
// * at least the static cast will fail
AbstractBase<ConcreteClass3> instance;
I read it in my book
An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration.

Why does an interface needs to be redeclared?

I have an abstract base class and want to implement a function in the derived class. Why do I have to declare the function in the derived class again?
class base {
public:
virtual int foo(int) const = 0;
};
class derived : public base {
public:
int foo(int) const; // Why is this required?
};
int derived::foo(int val) const { return 2*val; }
Consider that the derived-class definition might be in a header, whereas its implementation may be in a source file. The header typically gets included in multiple locations ("translation units"), each of which will be compiled independently. If you didn't declare the override, then the compiler wouldn't know about it in any of those other translation units.
The intention of making a function pure virtual in Base class is that the derived class must override it and provide its own implementation.
Note that presence of an pure virtual function in the class makes that class an Abstract class. In simple terms the class acts as an interface for creating more concrete classes.One cannot create objects of an Abstract class.
If you do not override the pure virtual function in derived class then the derived class contains the inherited Base class pure virtual function only and it itself acts as an Abstract class too.Once your derived class is abstract it cannot be instantiated.
So in order that your derived class be instantiated it needs to override and hence declare the pure virtual function.
You might think the compiler can deduce that you're going to have to provide an implementation of derived::foo(), but derived could also be an abstract class (and in fact that's what you'll get if you dont declare foo() in derived)
It is to override the abstraction of the base class.
If you do not re-declare it, then your derived class is also an abstract class. If you do then you now have a non-abstract type of the base.
Because the hierarchy could have more layers.
struct Base {
virtual void foo() const = 0;
virtual void bar() const = 0;
};
struct SuperBase: Base {
virtual void bar() const override;
};
struct Concrete: SuperBase {
virtual void foo() const override;
};
Here, SuperBase does not provide an implementation for foo, this needs be indicated somehow.
While you can't instantiate a class with pure virtual functions, you can still create a class like this:
class base {
public:
virtual int foo(int) const = 0;
};
class derived : public base {
public:
};
class very_derived : public derived {
public:
virtual int foo(int) const { return 2; }
};
The derived class is still an abstract class, it can't be instantiated since it doesn't override foo. You need to declare a non-pure virtual version of foo before you can instantiate the class, even if you don't define foo right away.

Can I use `abstract` keyword in C++ class

Can we write abstract keyword in C++ class?
#define abstract
No.
Pure virtual functions, in C++, are declared as:
class X
{
public:
virtual void foo() = 0;
};
Any class having at least one of them is considered abstract.
No, C++ has no keyword abstract. However, you can write pure virtual functions; that's the C++ way of expressing abstract classes.
It is a keyword introduced as part of the C++/CLI language spefication for the .NET framework.
no, you need to have at least one pure virtual function in a class to be abstract.
Here is a good reference cplusplus.com
As others point out, if you add a pure virtual function, the class becomes abstract.
However, if you want to implement an abstract base class with no pure virtual members, I find it useful to make the constructor protected. This way, you force the user to subclass the ABC to use it.
Example:
class Base
{
protected:
Base()
{
}
public:
void foo()
{
}
void bar()
{
}
};
class Child : public Base
{
public:
Child()
{
}
};
actually keyword abstract exists in C++ (VS2010 at least) and I found it can be used to declare a class/struct as non-instantiated.
struct X abstract {
static int a;
static void foX(){};
};
int X::a = 0;
struct Y abstract : X { // something static
};
struct Z : X { // regular class
};
int main() {
X::foX();
Z Zobj;
X Xobj; // error C3622
}
MSDN: https://msdn.microsoft.com/en-us/library/b0z6b513%28v=vs.110%29.aspx
There is no keyword 'abstract' but a pure virtual function turns a class in to abstract class which one can extend and re use as an interface.
No, you can't use abstract as a keyword because there is no such keyword available in C++.
If you want to declare a C++ class as abstract, you can declare at least one function as a pure virtual function.
But in derived class you must provide a definition otherwise its give compilation error.
Example:
class A
{
public:
virtual void sum () = 0;
};
note:
You can used abstract as a variable name, class name because, as I told you, abstract is not a keyword in C++.
No, C++ has no keyword abstract. However, you can write pure virtual functions; that's the C++ way of expressing abstract classes. It is a keyword introduced as part of the C++/CLI language spefication for the .NET framework. You need to have at least one pure virtual function in a class to be abstract.
class SomeClass {
public:
virtual void pure_virtual() = 0; // a pure virtual function
};
Most C++ compilers do not have an abstract keyword.
A Cheap Abstract Keyword
Although you could define a macro with that name like so:
#define abstract
class foo abstract { ... };
It would have absolutely no effect on the class, however, if any variable, function, anything is named "abstract", that #define is not going to make your code happy.
Create an Abstract Class
As mentioned by others, you can force a class to be abstract by creating a Pure Virtual function and set it to 0 like so:
class foo
{
virtual void func() = 0;
};
foo::func() { /* some default code [not required] */ }
Pro: Since even a pure virtual function can have a body, you can make a class abstract even though the very function you defined as abstract (pure virtual) is defined. However, contrary to the other virtual functions, having a body is not required of pure virtual functions.
Con: You are forced to create at least one pure virtual function and that forces all derived classes to define that function to not be viewed as abstract. If you anyway have such a function, then great! But often, this is not the case.
The Correct Way
There is actually an astute way of creating an abstract class which is not well known. You still have to create a pure virtual function... and the fact is that the destructor can be a pure virtual function! There is ALWAYS a destructor in a class that uses the virtual keyword, so there is no hesitation here.
class foo {
virtual ~foo() = 0;
};
foo * f(new foo); // this fails, foo is abstract
The classes that derive from foo must now declare an explicit destructor (newer compilers properly create one implicitly, but it would still be a pure virtual function) which is not pure virtual like so:
class bar : public foo {
virtual ~bar() override {}
};
Note that we do not have an abstract keyword, but we do have an override keyword, which is super useful so when a function signature changes, you cannot compile until all the classes that derive from your base class have their virtual functions updated accordingly.
Effect of the Default Destructor
An interesting aspect to using the destructor as the pure virtual function is that derived classes automatically get a destructor (if you don't define one) and means your derived classes are automatically non-abstract (assuming only the destructor is a pure virtual in the base class).
In other words, you could declare bar with:
class bar : public foo {
void some_function();
};
and it automatically is not abstract because the default destructor is not abstract as it will more or less look like this:
virtual ~bar() override {}
if you don't define it yourself.
In other words, if you want to define another layer which still is abstract (i.e. if you want new bar to fail to compile), then you must declare your own destructor and mark it as a pure virtual:
class bar : public foo {
virtual ~bar() override = 0;
void some_function();
};
bar::~bar() {}
(the {} and = 0 can't be used together so you have to declare the destructor body separately.)
Abstract keyword presents in java, similar abstraction we can achieve in C++ by using pure virtual function.

Virtual/pure virtual explained

What exactly does it mean if a function is defined as virtual and is that the same as pure virtual?
From Wikipedia's Virtual function
...
In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part of the (runtime) polymorphism portion of object-oriented programming (OOP). In short, a virtual function defines a target function to be executed, but the target might not be known at compile time.
Unlike a non-virtual function, when a virtual function is overridden the most-derived version is used at all levels of the class hierarchy, rather than just the level at which it was created. Therefore if one method of the base class calls a virtual method, the version defined in the derived class will be used instead of the version defined in the base class.
This is in contrast to non-virtual functions, which can still be overridden in a derived class, but the "new" version will only be used by the derived class and below, but will not change the functionality of the base class at all.
whereas..
A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract.
When a pure virtual method exists, the class is "abstract" and can not be instantiated on its own. Instead, a derived class that implements the pure-virtual method(s) must be used. A pure-virtual isn't defined in the base-class at all, so a derived class must define it, or that derived class is also abstract, and can not be instantiated. Only a class that has no abstract methods can be instantiated.
A virtual provides a way to override the functionality of the base class, and a pure-virtual requires it.
I'd like to comment on Wikipedia's definition of virtual, as repeated by several here. [At the time this answer was written,] Wikipedia defined a virtual method as one that can be overridden in subclasses. [Fortunately, Wikipedia has been edited since, and it now explains this correctly.] That is incorrect: any method, not just virtual ones, can be overridden in subclasses. What virtual does is to give you polymorphism, that is, the ability to select at run-time the most-derived override of a method.
Consider the following code:
#include <iostream>
using namespace std;
class Base {
public:
void NonVirtual() {
cout << "Base NonVirtual called.\n";
}
virtual void Virtual() {
cout << "Base Virtual called.\n";
}
};
class Derived : public Base {
public:
void NonVirtual() {
cout << "Derived NonVirtual called.\n";
}
void Virtual() {
cout << "Derived Virtual called.\n";
}
};
int main() {
Base* bBase = new Base();
Base* bDerived = new Derived();
bBase->NonVirtual();
bBase->Virtual();
bDerived->NonVirtual();
bDerived->Virtual();
}
What is the output of this program?
Base NonVirtual called.
Base Virtual called.
Base NonVirtual called.
Derived Virtual called.
Derived overrides every method of Base: not just the virtual one, but also the non-virtual.
We see that when you have a Base-pointer-to-Derived (bDerived), calling NonVirtual calls the Base class implementation. This is resolved at compile-time: the compiler sees that bDerived is a Base*, that NonVirtual is not virtual, so it does the resolution on class Base.
However, calling Virtual calls the Derived class implementation. Because of the keyword virtual, the selection of the method happens at run-time, not compile-time. What happens here at compile-time is that the compiler sees that this is a Base*, and that it's calling a virtual method, so it insert a call to the vtable instead of class Base. This vtable is instantiated at run-time, hence the run-time resolution to the most-derived override.
I hope this wasn't too confusing. In short, any method can be overridden, but only virtual methods give you polymorphism, that is, run-time selection of the most derived override. In practice, however, overriding a non-virtual method is considered bad practice and rarely used, so many people (including whoever wrote that Wikipedia article) think that only virtual methods can be overridden.
The virtual keyword gives C++ its' ability to support polymorphism. When you have a pointer to an object of some class such as:
class Animal
{
public:
virtual int GetNumberOfLegs() = 0;
};
class Duck : public Animal
{
public:
int GetNumberOfLegs() { return 2; }
};
class Horse : public Animal
{
public:
int GetNumberOfLegs() { return 4; }
};
void SomeFunction(Animal * pAnimal)
{
cout << pAnimal->GetNumberOfLegs();
}
In this (silly) example, the GetNumberOfLegs() function returns the appropriate number based on the class of the object that it is called for.
Now, consider the function 'SomeFunction'. It doesn't care what type of animal object is passed to it, as long as it is derived from Animal. The compiler will automagically cast any Animal-derived class to a Animal as it is a base class.
If we do this:
Duck d;
SomeFunction(&d);
it'd output '2'. If we do this:
Horse h;
SomeFunction(&h);
it'd output '4'. We can't do this:
Animal a;
SomeFunction(&a);
because it won't compile due to the GetNumberOfLegs() virtual function being pure, which means it must be implemented by deriving classes (subclasses).
Pure Virtual Functions are mostly used to define:
a) abstract classes
These are base classes where you have to derive from them and then implement the pure virtual functions.
b) interfaces
These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.
In a C++ class, virtual is the keyword which designates that, a method can be overridden (i.e. implemented by) a subclass. For example:
class Shape
{
public:
Shape();
virtual ~Shape();
std::string getName() // not overridable
{
return m_name;
}
void setName( const std::string& name ) // not overridable
{
m_name = name;
}
protected:
virtual void initShape() // overridable
{
setName("Generic Shape");
}
private:
std::string m_name;
};
In this case a subclass can override the the initShape function to do some specialized work:
class Square : public Shape
{
public:
Square();
virtual ~Square();
protected:
virtual void initShape() // override the Shape::initShape function
{
setName("Square");
}
}
The term pure virtual refers to virtual functions that need to be implemented by a subclass and have not been implemented by the base class. You designate a method as pure virtual by using the virtual keyword and adding a =0 at the end of the method declaration.
So, if you wanted to make Shape::initShape pure virtual you would do the following:
class Shape
{
...
virtual void initShape() = 0; // pure virtual method
...
};
By adding a pure virtual method to your class you make the class an abstract base class
which is very handy for separating interfaces from implementation.
"Virtual" means that the method may be overridden in subclasses, but has an directly-callable implementation in the base class. "Pure virtual" means it is a virtual method with no directly-callable implementation. Such a method must be overridden at least once in the inheritance hierarchy -- if a class has any unimplemented virtual methods, objects of that class cannot be constructed and compilation will fail.
#quark points out that pure-virtual methods can have an implementation, but as pure-virtual methods must be overridden, the default implementation can't be directly called. Here is an example of a pure-virtual method with a default:
#include <cstdio>
class A {
public:
virtual void Hello() = 0;
};
void A::Hello() {
printf("A::Hello\n");
}
class B : public A {
public:
void Hello() {
printf("B::Hello\n");
A::Hello();
}
};
int main() {
/* Prints:
B::Hello
A::Hello
*/
B b;
b.Hello();
return 0;
}
According to comments, whether or not compilation will fail is compiler-specific. In GCC 4.3.3 at least, it won't compile:
class A {
public:
virtual void Hello() = 0;
};
int main()
{
A a;
return 0;
}
Output:
$ g++ -c virt.cpp
virt.cpp: In function ‘int main()’:
virt.cpp:8: error: cannot declare variable ‘a’ to be of abstract type ‘A’
virt.cpp:1: note: because the following virtual functions are pure within ‘A’:
virt.cpp:3: note: virtual void A::Hello()
A virtual function is a member function that is declared in a base class and that is redefined by derived class. Virtual function are hierarchical in order of inheritance.
When a derived class does not override a virtual function, the function defined within its base class is used.
A pure virtual function is one that contains no definition relative to the base class.
It has no implementation in the base class. Any derived class must override this function.
How does the virtual keyword work?
Assume that Man is a base class, Indian is derived from man.
Class Man
{
public:
virtual void do_work()
{}
}
Class Indian : public Man
{
public:
void do_work()
{}
}
Declaring do_work() as virtual simply means: which do_work() to call will be determined ONLY at run-time.
Suppose I do,
Man *man;
man = new Indian();
man->do_work(); // Indian's do work is only called.
If virtual is not used, the same is statically determined or statically bound by the compiler, depending on what object is calling. So if an object of Man calls do_work(), Man's do_work() is called EVEN THOUGH IT POINTS TO AN INDIAN OBJECT
I believe that the top voted answer is misleading - Any method whether or not virtual can have an overridden implementation in the derived class. With specific reference to C++ the correct difference is run-time (when virtual is used) binding and compile-time (when virtual is not used but a method is overridden and a base pointer is pointed at a derived object) binding of associated functions.
There seems to be another misleading comment that says,
"Justin, 'pure virtual' is just a term (not a keyword, see my answer
below) used to mean "this function cannot be implemented by the base
class."
THIS IS WRONG!
Purely virtual functions can also have a body AND CAN BE IMPLEMENTED! The truth is that an abstract class' pure virtual function can be called statically! Two very good authors are Bjarne Stroustrup and Stan Lippman.... because they wrote the language.
Simula, C++, and C#, which use static method binding by default, the programmer can specify that particular methods should use dynamic binding by labeling them as virtual.
Dynamic method binding is central to object-oriented programming.
Object oriented programming requires three fundamental concepts: encapsulation, inheritance, and dynamic method binding.
Encapsulation allows the implementation details of an
abstraction to be hidden behind a
simple interface.
Inheritance allows a new abstraction to be defined as an
extension or refinement of some
existing abstraction, obtaining some
or all of its characteristics
automatically.
Dynamic method binding allows the new abstraction to display its new
behavior even when used in a context
that expects the old abstraction.
Virtual methods CAN be overridden by deriving classes, but need an implementation in the base class (the one that will be overridden)
Pure virtual methods have no implementation the base class. They need to be defined by derived classes. (So technically overridden is not the right term, because there's nothing to override).
Virtual corresponds to the default java behaviour, when the derived class overrides a method of the base class.
Pure Virtual methods correspond to the behaviour of abstract methods within abstract classes. And a class that only contains pure virtual methods and constants would be the cpp-pendant to an Interface.
Pure Virtual Function
try this code
#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{
public:
virtual void sayHellow()=0;
};
class anotherClass:aClassWithPureVirtualFunction
{
public:
void sayHellow()
{
cout<<"hellow World";
}
};
int main()
{
//aClassWithPureVirtualFunction virtualObject;
/*
This not possible to create object of a class that contain pure virtual function
*/
anotherClass object;
object.sayHellow();
}
In class anotherClass remove the function sayHellow and run the code. you will get error!Because when a class contain a pure virtual function, no object can be created from that class and it is inherited then its derived class must implement that function.
Virtual function
try another code
#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{
public:
virtual void sayHellow()
{
cout<<"from base\n";
}
};
class anotherClass:public aClassWithPureVirtualFunction
{
public:
void sayHellow()
{
cout<<"from derived \n";
}
};
int main()
{
aClassWithPureVirtualFunction *baseObject=new aClassWithPureVirtualFunction;
baseObject->sayHellow();///call base one
baseObject=new anotherClass;
baseObject->sayHellow();////call the derived one!
}
Here the sayHellow function is marked as virtual in base class.It say the compiler that try searching the function in derived class and implement the function.If not found then execute the base one.Thanks
"A virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature" - wikipedia
This is not a good explanation for virtual functions. Because, even if a member is not virtual, inheriting classes can override it. You can try and see it yourself.
The difference shows itself when a function take a base class as a parameter. When you give an inheriting class as the input, that function uses the base class implementation of the overriden function. However, if that function is virtual, it uses the one that is implemented in the deriving class.
Virtual functions must have a definition in base class and also in derived class but not necessary, for example ToString() or toString() function is a Virtual so you can provide your own implementation by overriding it in user-defined class(es).
Virtual functions are declared and defined in normal class.
Pure virtual function must be declared ending with "= 0" and it can only be declared in abstract class.
An abstract class having a pure virtual function(s) cannot have a definition(s) of that pure virtual functions, so it implies that implementation must be provided in class(es) that derived from that abstract class.