Why use an abstract class in object-oriented programming?

In summary: OOO...programming projects that grow & evolve without any well-planned & well-maintained architecture.The abstract class is a way of defining a contract between the class designer and the users of that class. It's a way of forcing a contract between the class designer and the users of that class. If we wish to create a concrete class (a class that can be instantiated) from an abstract class we must declare and define a matching member function for each abstract member function of the base class.
  • #1
FallenApple
566
61
So what is the purpose of an Abstract Class? Can I not get the same things by doing subclasses?

For example. I can create a class called Vector_Space and then a subclass called Euclidean_Space

We all know that Euclidean space is just a particular type of vector space. So I can just write the program once for Vector_Space and then just code in the extra stuff for Euclidean_Space

So why would I want an abstract class when I can just do the abstraction by inheritance instead? I can just chain the inheritance until I've abstracted away most of the structure.
As an example,
...Group->...Module->Vector_Space->Euclidean_Space
 
  • Like
Likes atyy
Technology news on Phys.org
  • #2
This is an example of why I consider C++ to be the most elegant of Oop programming languages.
There are often several ways of describing data objects, so the programmer can choose whichever way they think describes it best.
 
  • Like
Likes atyy
  • #3
FallenApple said:
So what is the purpose of an Abstract Class? Can I not get the same things by doing subclasses?
No, there's a subtle difference between an abstract class and a class that is merely a subclass,
i.e., a class that inherits from another class. The basic difference is that an abstract class is not intended to be instantiated. If the abstract class has at least one pure virtual method, that method must be implemented by any class derived from the abstract class.
FallenApple said:
For example. I can create a class called Vector_Space and then a subclass called Euclidean_Space

We all know that Euclidean space is just a particular type of vector space. So I can just write the program once for Vector_Space and then just code in the extra stuff for Euclidean_Space
Or you could make Vector_Space truly abstract, assuming you don't plan to create any instances of this class. You could make (virtual) methods that are common to all types of vector spaces, forcing any subclasses to implement these methods.

This article explains it nicely: https://en.wikibooks.org/wiki/C++_Programming/Classes/Abstract_Classes
FallenApple said:
So why would I want an abstract class when I can just do the abstraction by inheritance instead? I can just chain the inheritance until I've abstracted away most of the structure.
As an example,
...Group->...Module->Vector_Space->Euclidean_Space
 
  • Like
Likes FallenApple
  • #4
OOP languages support a couple of design strategies:

1) You may have a collection of similar classes with many common methods but with a few methods that take the same arguments but are specific to the class.

Programmers will use the abstract class as the parent class and then subclass for the more specific classes. The abstract type tells the compiler to not allow you to instantiate the parent class directly but you can use it as a more generic datatype.

A simple example would be the Animal class as the parent of the Duck, Dog and Cat classes

http://www.techrepublic.com/article/intro-to-oop-understanding-classes-and-objects/

2) When classes have a similar behavior but not a common parent relationship then programmers will use the interface pattern which describes the methods that must be supported by the class in order to implement the interface.

A good example would be the Runnable interface in Java which requires a class to implement the run() method in order to be spun off as a separate thread.
 
  • Like
Likes FallenApple
  • #5
I like the answers by @Mark44 and @jedishrfu, and also the link to the Wikibooks article; in part because that article hints at a more general answer that I think could be fleshed out more. The hint is in statements such as this one:
In general an abstract class is used to define an implementation and is intended to be inherited from by concrete classes. It's a way of forcing a contract between the class designer and the users of that class. If we wish to create a concrete class (a class that can be instantiated) from an abstract class we must declare and define a matching member function for each abstract member function of the base class.

I am not the person to really explain this, because I haven't coded seriously in at least 10 years. But back when I did code, I was doing it partly for fun, and partly to support various projects in my work as contract a technical writer/editor; and for whatever reason I got heavily into reading about how OOP languages were meant to work from a philosophical POV, as well as how to build them from a "best practices" POV. So all this rings a very faint bell for me, from what seems a long time ago.

If you are just learning & doing coding by yourself, designing & building one-off programs, stuff like abstract classes may not seem important; but it becomes very important as projects get larger & you start to work in teams & the code itself starts to span many generations & implementations etc.; and/or will be ported to many platforms; etc. Old-style procedural code could and did turn into a horrible mess; and so will big OOP projects unless techniques & conventions are employed to prevent it. And I would consider abstract classes one of these devices.

So although I am sure someone else can explain it more accurately than I can, my guess is that in response to @FallenApple's question about the "purpose" of abstract classes, we might say that one purpose is to aid in constraining & guiding the design of the system (via using abstract classes for base classes), without constraining the implementation. And the more complex the system, the more useful this approach will be.

Most of my books on good coding practice are now in boxes at another location, but by Googling I did find a journal article that talks about this sort of thing - one of a zillion I'm sure; also it's quite old - 1991! - so it uses Smalltalk as its example language. The article is "Designing Reusable Classes," by Ralph E. Johnson & Brian Foote, Journal of Object-Oriented Programming, June/July 1988; here is the abstract; bold is mine; note much of what is described will seem somewhat dated:

Object-oriented programming is as much a different way of designing programs as it is a different way of designing programming languages. This paper describes what it is like to design systems in Smalltalk. In particular, since a major motivation for object-oriented programming is software reuse, this paper describes how classes are developed so that they will be reusable.​

And here is a short excerpt specifically talking about abstract classes & their use in building frameworks:

A class that is not abstract is concrete. In general, it is better to inherit from an abstract class than from a concrete class. A concrete class must provide a definition for its data representation, and some subclasses will need a different representation. Since an abstract class does not have to provide a data representation, future subclasses can use any representation without fear of conflicting with the one that they inherited.

Creating new abstract classes is very important, but is not easy. It is always easier to reuse a nicely packaged abstraction than to invent it. However, the process of programming in Smalltalk makes it easier to discover the important abstractions. A Smalltalk programmer always tries to create new classes by making them be subclasses of existing ones, since this is less work than creating a class from scratch. This often results in a class hierarchy whose top-most class is concrete. The top of a large class hierarchy should almost always be an abstract class, so the experienced programmer will then try to reorganize the class hierarchy and find the abstract class hidden in the concrete class. The result will be a new abstract class that can be reused many times in the future.

3. Toolkits and Frameworks

One of the most important kinds of reuse is reuse of designs. A collection of abstract classes can be used to express an abstract design. The design of a program is usually described in terms of the program's components and the way they interact. For example, a compiler can be described as consisting of a lexer, a parser, a symbol table, a type checker, and a code generator.

An object-oriented abstract design, also called a framework, consists of an abstract class for each major component. The interfaces between the components of the design are defined in terms of sets of messages. There will usually be a library of subclasses that can be used as components in the design. A compiler framework would probably have some concrete symbol table classes and some classes that generate code for common machines. In theory, code generators could be mixed with many different parsers. However, parsers and lexers would be closely matched. Thus, some parts of a framework place more constraints on each other than others.​

Etc. As I say no doubt much of this is dated, but it does suggest the larger concept; maybe someone else can give an example that is more current or illustrates the advantages more specifically, e.g. the difference between an abstract class & an interface in terms of design, etc. Also I gather that frameworks are still in use as a general organizing concept - here is the Wikipedia article on "Software frameworks": https://en.wikipedia.org/wiki/Software_framework

---

P.S. Brian Foote's name as one of the authors of the paper sounded very familiar to me, so I tried to look him up in Wikipedia & found he was mentioned only in an article titled "Big ball of mud" (!). A more general search finds that he is still active in the field, or at least he was as of 2009, and still writing & talking about larger patterns in software; here is a 2009 interview with him in informIT, "Brian Foote on the 15th Anniversary of Design Patterns." So probably I must have come across his name years ago & just don't remember where. A little bio on him goes w/ that interview: "Brian Foote has been writing programs professionally for over twenty years and has been doing research on object-oriented programming, languages, frameworks, architecture, evolution, and refactoring since the mid 1980s. He is also a consultant who has been active in the patterns community since its inception and was program chair of the PLoP '96 conference." So yeah, abstract classes etc.
 
Last edited:
  • Like
Likes FallenApple
  • #6
P.S. Here's an example of the sort of book I used to read about coding conventions; this one was published in 2008, when "agile" development was in full swing: Clean Code: A Handbook of Agile Software Craftmanship. And here is a typical example of the philosophizing I was talking about in regard to "best practices" - this is a "gotcha" in a list of same from the section on abstraction, followed by corrective advice - bold is mine:

Code at Wrong Level of Abstraction
It is important to create abstractions that separate higher level general concepts from lower level detailed concepts. Sometimes we do this by creating abstract classes to hold the higher level concepts and derivatives to hold the lower level concepts. When we do this, we need to make sure that the separation is complete. We want all the lower level concepts to be in the derivatives and all the higher level concepts to be in the base class.

For example, constants, variables, or utility functions that pertain only to the detailed implementation should not be in the base class. The base class should know nothing about them.

This rule also pertains to source files, components, and modules. Good software design requires that we separate concepts at different levels and place them in different containers. Some of these containers are base classes or derivatives and sometimes they are source files, modules, or components. Whatever the case may be, the separation needs to be complete. We don't want lower and higher level concepts mixed together.

Consider the following code: [example follows of poor separation]​

Etc. and so forth.
 
Last edited:
  • Like
Likes FallenApple
  • #7
FallenApple said:
So what is the purpose of an Abstract Class? Can I not get the same things by doing subclasses?

For example. I can create a class called Vector_Space and then a subclass called Euclidean_Space

We all know that Euclidean space is just a particular type of vector space. So I can just write the program once for Vector_Space and then just code in the extra stuff for Euclidean_Space

So why would I want an abstract class when I can just do the abstraction by inheritance instead? I can just chain the inheritance until I've abstracted away most of the structure.
As an example,
...Group->...Module->Vector_Space->Euclidean_Space
The key is the notion is the setting up a contract. If I have an abstract class "MotorVehicle" and abstract subclass "Sedan" with derived classes such as Impala2017 and SClass300_2017, I can immediately start writing code to use these objects. For example, I may have a pure virtual function GetTrunkSpace(). I can write a program today (2017) that relies on GetTrunkSpace(). Years from now, you can create a class Tesla2022 and my old program will still work with your new class.
 
  • Like
Likes FallenApple
  • #8
.Scott said:
The key is the notion is the setting up a contract. If I have an abstract class "MotorVehicle" and abstract subclass "Sedan" with derived classes such as Impala2017 and SClass300_2017, I can immediately start writing code to use these objects. For example, I may have a pure virtual function GetTrunkSpace(). I can write a program today (2017) that relies on GetTrunkSpace(). Years from now, you can create a class Tesla2022 and my old program will still work with your new class.

Assuming the new Tesla will have a trunk...
 
  • #9
It's meant to act as a template for you to fill in. One of the most common times this is used is for data access. You might create an abstract class like this:

Code:
class data_access {
public:
    int getInt(const char * key) = 0;
    void setInt(const char * key, int value) = 0;
};

Then you'll have all of your programmers use that whenever they need to store something, how it stores it, they don't care about. Then, you as a utility program might implement it differently depending on the circumstances. You may end up writing something like this:

Code:
class data_access_mysql : public data_access {
public:
     int getInt(const char * key){
        return mysql_query("SELECT value FROM vars WHERE KEY = %s", key).at(0).as_int();
     }
     void setInt(const char * key, int value){
        if (!mysql_query("UPDATE vars SET value=%d WHERE KEY = %s", value, key)){
            mysql_query("INSERT VALUES (%s, %d) INTO vars", key, value)
        }
     }
};
But then BAM! Customer wants to use Oracle instead of Mysql. Instead of going through all of the code and making messy preprocessor switches, you just write a new data access object and drop it in.
 
  • Like
Likes Reiten and FallenApple
  • #10
UsableThought said:
I like the answers by @Mark44 and @jedishrfu, and also the link to the Wikibooks article; in part because that article hints at a more general answer that I think could be fleshed out more. The hint is in statements such as this one:I am not the person to really explain this, because I haven't coded seriously in at least 10 years. But back when I did code, I was doing it partly for fun, and partly to support various projects in my work as contract a technical writer/editor; and for whatever reason I got heavily into reading about how OOP languages were meant to work from a philosophical POV, as well as how to build them from a "best practices" POV. So all this rings a very faint bell for me, from what seems a long time ago.

If you are just learning & doing coding by yourself, designing & building one-off programs, stuff like abstract classes may not seem important; but it becomes very important as projects get larger & you start to work in teams & the code itself starts to span many generations & implementations etc.; and/or will be ported to many platforms; etc. Old-style procedural code could and did turn into a horrible mess; and so will big OOP projects unless techniques & conventions are employed to prevent it. And I would consider abstract classes one of these devices.

So although I am sure someone else can explain it more accurately than I can, my guess is that in response to @FallenApple's question about the "purpose" of abstract classes, we might say that one purpose is to aid in constraining & guiding the design of the system (via using abstract classes for base classes), without constraining the implementation. And the more complex the system, the more useful this approach will be.

Most of my books on good coding practice are now in boxes at another location, but by Googling I did find a journal article that talks about this sort of thing - one of a zillion I'm sure; also it's quite old - 1991! - so it uses Smalltalk as its example language. The article is "Designing Reusable Classes," by Ralph E. Johnson & Brian Foote, Journal of Object-Oriented Programming, June/July 1988; here is the abstract; bold is mine; note much of what is described will seem somewhat dated:

Object-oriented programming is as much a different way of designing programs as it is a different way of designing programming languages. This paper describes what it is like to design systems in Smalltalk. In particular, since a major motivation for object-oriented programming is software reuse, this paper describes how classes are developed so that they will be reusable.​

And here is a short excerpt specifically talking about abstract classes & their use in building frameworks:

A class that is not abstract is concrete. In general, it is better to inherit from an abstract class than from a concrete class. A concrete class must provide a definition for its data representation, and some subclasses will need a different representation. Since an abstract class does not have to provide a data representation, future subclasses can use any representation without fear of conflicting with the one that they inherited.

Creating new abstract classes is very important, but is not easy. It is always easier to reuse a nicely packaged abstraction than to invent it. However, the process of programming in Smalltalk makes it easier to discover the important abstractions. A Smalltalk programmer always tries to create new classes by making them be subclasses of existing ones, since this is less work than creating a class from scratch. This often results in a class hierarchy whose top-most class is concrete. The top of a large class hierarchy should almost always be an abstract class, so the experienced programmer will then try to reorganize the class hierarchy and find the abstract class hidden in the concrete class. The result will be a new abstract class that can be reused many times in the future.

3. Toolkits and Frameworks

One of the most important kinds of reuse is reuse of designs. A collection of abstract classes can be used to express an abstract design. The design of a program is usually described in terms of the program's components and the way they interact. For example, a compiler can be described as consisting of a lexer, a parser, a symbol table, a type checker, and a code generator.

An object-oriented abstract design, also called a framework, consists of an abstract class for each major component. The interfaces between the components of the design are defined in terms of sets of messages. There will usually be a library of subclasses that can be used as components in the design. A compiler framework would probably have some concrete symbol table classes and some classes that generate code for common machines. In theory, code generators could be mixed with many different parsers. However, parsers and lexers would be closely matched. Thus, some parts of a framework place more constraints on each other than others.​

Etc. As I say no doubt much of this is dated, but it does suggest the larger concept; maybe someone else can give an example that is more current or illustrates the advantages more specifically, e.g. the difference between an abstract class & an interface in terms of design, etc. Also I gather that frameworks are still in use as a general organizing concept - here is the Wikipedia article on "Software frameworks": https://en.wikipedia.org/wiki/Software_framework

---

P.S. Brian Foote's name as one of the authors of the paper sounded very familiar to me, so I tried to look him up in Wikipedia & found he was mentioned only in an article titled "Big ball of mud" (!). A more general search finds that he is still active in the field, or at least he was as of 2009, and still writing & talking about larger patterns in software; here is a 2009 interview with him in informIT, "Brian Foote on the 15th Anniversary of Design Patterns." So probably I must have come across his name years ago & just don't remember where. A little bio on him goes w/ that interview: "Brian Foote has been writing programs professionally for over twenty years and has been doing research on object-oriented programming, languages, frameworks, architecture, evolution, and refactoring since the mid 1980s. He is also a consultant who has been active in the patterns community since its inception and was program chair of the PLoP '96 conference." So yeah, abstract classes etc.

It's starting to make more sense. Let's see if I have this correct.

The most general notion of under going motion is to move. But the action move is ill defined. It is merely a concept. One could fly, drive, crawl, walk, run, etc. Maybe run is a special case of walk, but with faster speed, and maybe walk is a special case of crawl, but with two legs only, whereas fly is different from any of those. So at the very top of the hierachy, move can no longer be defined by a specific action more particular than simply to move. So hence , the top level has to be abstract.
 
  • #11
FallenApple said:
It's starting to make more sense. Let's see if I have this correct.

The most general notion of under going motion is to move. But the action move is ill defined. It is merely a concept. One could fly, drive, crawl, walk, run, etc. Maybe run is a special case of walk, but with faster speed, and maybe walk is a special case of crawl, but with two legs only, whereas fly is different from any of those. So at the very top of the hierachy, move can no longer be defined by a specific action more particular than simply to move. So hence , the top level has to be abstract.
Exactly.

Another very common use is for stepping through lots of different types of objects. Often in design you'll end up with a lot of little utility classes that you want to have looping constantly, but don't really warrant each having a thread so you give them all an abstract class above them something like this:

Code:
class looper_object {
public:
   virtual void setup() = 0;
   virtual void beforeStep() = 0;
   virtual void step() = 0;
   virtual void afterStep() = 0;
   bool isActive;
};

This is how things like game engines can have hundreds or thousands of objects all doing things, but I also use it for things like managing memory pools and polling sockets.
 
  • #12
FallenApple said:
So what is the purpose of an Abstract Class?
So why would I want an abstract class when I can just do the abstraction by inheritance instead?

An abstract class is simply an interface which you program against to obtain information from concrete classes. The reason you use one of these is to gain isolation. For example, you can create a factory pattern to switch out objects depending on say a user selecting a type of FTP/SFTP/FTPS. Another example is to do unit testing which requires isolation.
 
  • Like
Likes jim mcnamara
  • #14
jim mcnamara said:
the root of abstract class as a term derives from the concept data abstraction

I would be interested in further support for this claim. It's my impression that the two are quite different, and moreover I have never come across any evidence that the one evolved historically from the other.

The primer article you cite in your link explains data abstraction in C++ - but it also inadvertently makes clear that this isn't what the OP (@FallenApple) asked about in his opening post. I think this is a "difference that makes a difference."

It's part of the general nature of OOP to facilitate encapsulation, or "black boxes," so that ideally you can build or revise your objects however you like without telling anyone else, since the internals are hidden. Data abstraction is a way of doing this. In fact at that same primer site, there is a topic about data encapsulation in C++; and that topic also mentions data abstraction; and also both topics discuss public vs. private members inside a class. All good, but nothing to do with abstract classes; those are a different mechanism.

Unfortunately I don't know of sufficiently authoritative sources myself to see if historically "this usage of 'abstract' evolved from that one" etc. Even so here's a bit of flotsam off the web that supports my contention: an entry on Abstract Data Types Versus Abstract Classes, from DevX.com. It's short enough that I will quote it here in full; I have bolded some of the most relevant points:

The terms abstract data type and abstract class refer to two entirely different concepts, although both of them use the word 'abstract' due to a historical accident. An abstract data type (also called a concrete type) is a self-contained, user-defined type that bundles data with a set of related operations. It behaves in the same way as a built-in type does. However, it does not inherit from other classes, nor does it serve as the base for other derived classes. Some examples of abstract data types or concrete types include std::string, std::complex, and std::vector. In contrast, an abstract class is anything but an abstract data type. An abstract class is a class that has at least one pure virtual member function. It is not a data type (normally, abstract classes do not contain any data members), nor can you instantiate an object thereof. An abstract class is merely a skeletal interface, which specifies a set of services that its subclasses implement. Unfortunately, the distinction between the two concepts is often confused. Many people erroneously use the term abstract data type when they actually refer to an abstract class.​
 
Last edited:
  • #15
Try this Stroustrup paper from his home page:
www.stroustrup.com/whatis.pdf

It deals with exactly the subject of abstraction of data and OOP concepts. Interpret as you will.
 
  • #16
jim mcnamara said:
Try this Stroustrup paper from his home page:
www.stroustrup.com/whatis.pdf

It deals with exactly the subject of abstraction of data and OOP concepts. Interpret as you will.

Now, that is a good source. Thanks for posting it, I'll look through it.
 
  • #17
My take on it is in the tutorial link - abstract classes are used to allow hiding program data and program text, but treating each instantiation with a common set of requirements or rules, if you like.
 
  • #18
jim mcnamara said:
My take on it is in the tutorial link - abstract classes are used to allow hiding program data and program text, but treating each instantiation with a common set of requirements or rules, if you like.

[EDITED AFTER A LITTLE MORE THOUGHT] I guess that would be one way of defining the effect of an abstract class? But it's not how I would have put it; which doesn't mean you're wrong; we may be talking at cross purposes.

I will say that I just want through that paper and didn't find anything that addresses abstract classes as I understand them & their usage, from the reading I've done elsewhere (which is more recent & in the form of books on programming practice in group environments). It was an interesting read, though.

Beyond that I have done a little more poking around the web, and I just found another thing I was thinking might be the case - which is that C++ is not a particularly good language to choose for discussing abstract classes, because it was built for a certain amount of backward compatibility with C; and in some ways is not as fully OOP as, say, Java. For this let me cite an instructor's CS slide presentation - here is the link the PDF version: http://dave-reed.com/csc533.S16/Lectures/evolution.pdf - the slide is on the bottom of p. 22. It describes abstract classes using language I am familiar with (whereas I don't understand your definition above). I've bolded those parts; and also his caution about C++:

Abstract classes
there are times when you want to define a class hierarchy, but the parent class is incomplete (more of a placeholder)
- e.g., the Statement class from HW3
- want to be able to talk about a hierarchy of statements (including Assignment,
Output, If), but there is no "Statement"
an abstract class is a class in which some methods are specified but not implemented
- can provide some concrete fields & methods
- the keyword "abstract" identifies methods that must be implemented by a derived
class
- you can't create an object of an abstract class, but it does provide a framework for inheritance


note: you can define abstract classes in C++, but in a very kludgy way

Thinking about all this, examples from C++ vs. say from Java might lead to different discussions; so perhaps it would have helped if the OP had specified what language he was working in . . . although none of us remembered to ask him.
 
Last edited:
  • #19
UsableThought said:
I would be interested in further support for this claim. It's my impression that the two are quite different, and moreover I have never come across any evidence that the one evolved historically from the other.

The primer article you cite in your link explains data abstraction in C++ - but it also inadvertently makes clear that this isn't what the OP (@FallenApple) asked about in his opening post. I think this is a "difference that makes a difference."
The second paragraph of the tutorialspoint site jim linked to has the following:
Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation.By separating the interface from implementation, a single abstract class can have multiple implementations.
Since the OP asked about abstract classes, the link seems relevant to me.
 
Last edited:
  • #20
Mark44 said:
The second paragraph of the cplusplus.com site jim linked to has the following:

"Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation."

Since the OP asked about abstract classes, the link seems relevant to me.

To me again this misses the difference.

It is one thing to have an intention ("Hey everybody, let's separate our interface & our implementation via various techniques"), and another to have a specific mechanism that goes further and enforces separation by a narrowly hierarchical means; moreover, a mechanism designed into some languages (e.g. Java) but apparently not into others, e.g. it can only be "kludged" together (see edited version of my previous comment) in a language such as C++.

In other words they're not equivalent. You can have data abstraction in your language without having abstract classes, and having data abstraction in your language does not mean it also has abstract classes.

Beyond that, the key point the OP was actually asking about was even more specific: He asked "why use an abstract class when I can just use inheritance"? Which again is an issue which data abstraction is not strictly concerned with.

So again, if we ask, "Is this a difference (data abstraction vs. abstract class) that makes a difference?", I think the answer in modern team programming for quite a while has been "Yes." Abstract classes have specific purposes that are not adequately captured by the term "data abstraction."

I do see that it can be argued it's a quibble; and I'm not so sure why I'm so bent on arguing about it; it's not really that important. I will say that for me, encapsulation and the notion of black boxes that talk to each other seem the starting point for learning about OOP; whereas both data abstraction and abstract classes seem more like particular implementations of the larger conceptual view.

That's how I learned about OOP, at any rate; but I went a very irregular route. I was a technical writer who had to write documentation for things like Java-based web platforms (this is awhile back), so that 3rd party programmers could read the doco & learn how to build in the platform. And the only way I could succeed was to read up on Java and OOP so that I could interview the programmers at length, and also read the code itself. I then discovered that I enjoyed it & so did some more reading & started coding. However my own coding was mostly for fun rather than money, except for a few small jobs here & there.
 
Last edited:
  • #21
UsableThought said:
note: you can define abstract classes in C++, but in a very kludgy way
The "very kludgy way" is a matter of opinion, in my view. All that is required is to have one or more pure virtual functions.
UsableThought said:
It is one thing to have an intention ("Hey everybody, let's separate our interface & our implementation via various techniques"), and another to have a specific mechanism that goes further and enforces separation by a narrowly hierarchical means; moreover, a mechanism designed into some languages (e.g. Java) but apparently not into others, e.g. it can only be "kludged" together (see edited version of my previous comment) in a language such as C++.

In other words they're not equivalent. You can have data abstraction in your language without having abstract classes, and having data abstraction in your language does not mean it also has abstract classes.
Well, no, they're not the same, but you're comparing a broad concept (data abstraction) with a particular way that it can be realized in a programming language. This is akin to comparing the concept of integral data and the int data type in C, C++, and other languages.

In any case, we seem to be veering away from the OP's original question, which was about abstract classes and whether one could just use inheritance instead. Here's a link to an article on cplusplus.com that discusses abstract classes vs. interfaces: http://www.cplusplus.com/forum/beginner/157568/.
 
  • Like
Likes QuantumQuest, jim mcnamara and UsableThought
  • #22
Here is a simple example of using an abstract class.

Code:
#include "stdafx.h"
#include "Factory.h"

int main()
{
    const static int SAYHELLO = 1;
    const static int SAYGOODBYE = 2;

    CFactory factory;
    factory.runExample(SAYHELLO)->saySomething();
    factory.runExample(SAYGOODBYE)->saySomething();    return 0;
}

Code:
class CAbstractExample
{
public:
    virtual void saySomething() = 0;
};

Code:
#include "AbstractExample.h"
#include <iostream>

using namespace std;

class CGoodByeWorld : public CAbstractExample {

public:
    virtual void saySomething()
    {
        cout << "Goodbye World!" << endl;
    }

};

Code:
#include "AbstractExample.h"
#include <iostream>

using namespace std;

class ChelloWorld : public CAbstractExample {
   
public:
    virtual void saySomething()
    {
        cout << "Hello World!" << endl;
    }

};
 
  • #23
UsableThought said:
[EDITED AFTER A LITTLE MORE THOUGHT]

Thinking about all this, examples from C++ vs. say from Java might lead to different discussions; so perhaps it would have helped if the OP had specified what language he was working in . . . although none of us remembered to ask him.

Architecture is really the main factor when discussing interfaces and abstract classes.
 
  • #24
Mark44 said:
No, there's a subtle difference between an abstract class and a class that is merely a subclass,
i.e., a class that inherits from another class. The basic difference is that an abstract class is not intended to be instantiated. If the abstract class has at least one pure virtual method, that method must be implemented by any class derived from the abstract class.
Or you could make Vector_Space truly abstract, assuming you don't plan to create any instances of this class. You could make (virtual) methods that are common to all types of vector spaces, forcing any subclasses to implement these methods.

This article explains it nicely: https://en.wikibooks.org/wiki/C++_Programming/Classes/Abstract_Classes
What would be the point of creating a(n) (abstract) class that will not be instantiated? EDIT: Would you use it to define/create, e.g., desctructors or constructors, objects/classes you do not need to instantiate?
 
  • #25
WWGD said:
What would be the point of creating a(n) (abstract) class that will not be instantiated?
An abstract class is intended to be the base of one or more concrete classes that are derived from the abstract class. A concrete class would be instantiated, and would include functions that would override those in the abstract (base) class. See the Vehicle abstract class in this wiki page -- https://en.wikibooks.org/wiki/C++_Programming/Classes/Abstract_Classes. Because the Vehicle class has a virtual function (that must be overridden in any derived classes), the Vehicle class cannot be instantiated; i.e., no Vehicle objects can be created.
 
  • Like
Likes WWGD
  • #26
WWGD said:
What would be the point of creating a(n) (abstract) class that will not be instantiated? EDIT: Would you use it to define/create, e.g., desctructors or constructors, objects/classes you do not need to instantiate?
To provide a consistent interface for each subtype of an otherwise undefinable parent class.

Say you want to simulate a forest. You can instantiate a “new whitePine,” “new redMaple,” “new oak,” but never “new tree.” What the hell is a tree specifically? I don’t know, certainly not something that can be instantiated.
 
  • Like
Likes WWGD

What is an abstract class?

An abstract class is a type of class in object-oriented programming that cannot be instantiated. It serves as a base or template for other classes to inherit from.

What is the purpose of an abstract class?

The purpose of an abstract class is to provide a common structure and functionality for its subclasses. It allows for code reusability and promotes consistency in the design of related classes.

How is an abstract class different from a regular class?

An abstract class cannot be instantiated, while a regular class can be. Additionally, an abstract class can contain both abstract and non-abstract methods, while a regular class can only contain non-abstract methods.

When should I use an abstract class?

An abstract class should be used when you want to create a base class that will be inherited by multiple subclasses. It is especially useful when there is shared functionality among these subclasses.

Can an abstract class have a constructor?

Yes, an abstract class can have a constructor. However, it cannot be used to instantiate the abstract class itself. Instead, it is used to initialize the variables of its subclasses.

Similar threads

  • Programming and Computer Science
2
Replies
43
Views
2K
  • Programming and Computer Science
Replies
10
Views
947
  • Programming and Computer Science
Replies
10
Views
1K
  • Programming and Computer Science
Replies
25
Views
3K
  • Programming and Computer Science
2
Replies
35
Views
2K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
2
Replies
65
Views
2K
  • Programming and Computer Science
Replies
5
Views
759
  • Programming and Computer Science
Replies
23
Views
1K
  • Programming and Computer Science
2
Replies
36
Views
2K
Back
Top