In C++ why a pure function must be virtual? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have searched on google and here but I can not understand why a pure function in a class must be virtual. I understand maybe it is not very useful declare a "normal function" as pure but I don't think is a nonsense. I mean, the word "pure" is there just to declare an abstract class. Ok, I can not use polymorphism with that pure normal function but the main reason (declare a class as abstract) is reached anyway.
Am I wrong?

There is no requirement that a pure function be virtual. If you're thinking of the term "pure virtual function", "pure" applies to "virtual" there; the function is purely virtual. It's a different use of the word "pure".
I mean, the word "pure" is there just to declare an abstract class.
It's not. The reason for declaring a pure virtual function is not to prevent instantiation of the enclosing class; it's to ensure that concrete subclasses implement the method, usually because the abstract class cannot provide a reasonable implementation.
Ok, I can not use polymorphism with that pure normal function but the main reason (declare a class as abstract) is reached anyway.
If you're looking for a way to declare a class abstract without any pure virtual functions, C++ does not have dedicated syntax for that. The suggestions I've seen are to declare and implement a pure virtual destructor (you can do that), or to make the constructor protected (but making the constructor protected won't make your class pass std::is_abstract). In any case, it wouldn't make much sense to attach the syntax for that to arbitrary member functions; something like class Foo = 0 { ... }; would make more sense.

The only reason you'd want to have a "pure function" is to make sure subclasses that inherit from this class define an implementation of this function. If you would allow pure functions to be non-virtual and thus not being able to be overriden they are basically pointless to have.

Related

E0322: object of abstract class type "" is not allowed [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I have a pure virtual function in my header file and a static class instance:
static Class mInstance;
I get the following error:
object of abstract class type "Class" is not allowed: function "" is a
pure virtual function.
What does this mean and how can I fix this?
Some more details:
My wish is to use the mInstance variable in other non-derived classes. The pure virtual function is being overriden by derived classes. Can I ask what kind of details I should provide? The mInstance variable is being used with a FactoryMethod that I wrote.
When you create an abstract class you are telling the compiler that there is no reason to create an instance of the class itself. This is usually done when you define an interface - set of methods and or fields for a base class that should work for various inherited classes but not base itself. So compiler helps you to avoid unintentional mistakes and does not allow to create an instance. So there are 2 possible solutions:
you made your class abstract by mistake and it should not be. Solution is simple just make all virtual functions not pure and implement them
your class should be abstract indeed. Then you should not have instance of the class, static or not. Usually when you have interface you work with pointer or reference to the base class and assign them to derived class that implements the interface. What should be done in your case is not clear as we do not have enough information, simplest in your case to make that static variable a pointer (probably a smart one) and assign it to an instance to derived class somewhere.

What are the risks of not implementing a virtual method of my parent class? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am pretty new to both the OOP and the C++ language.
Recently I have been given the task of come up with an object oriented design -which I guess I have done quite ok so far considering my lack of knowledge on the subject. And since I want to keep performing either like I have done so far or better, I want to get my doubt cleared.
I made a design in which the base class offers two virtual functions. Some children implements both virtual functions of their parent, but some others implement only one.
Now, I know that it is not the best / clean design somebody can come up with, and that if I do not implement (in some children) one of these virtual methods I might get warnings from the compiler. I know I can implement the methods, and when they are not needed they could simply return an exception, or simply do nothing.
With all that said, my doubt/question is: What is the actual risk of not implementing one of these virtual methods in the children? What happens on the object which does not have a virtual method's implementation of its parent? I am looking for a rather deep insight - I mean, I am looking for an understanding on a object's guts level so to say.
If an explanation is not possible to be given, any reference where to possible look at will be equally Welcomed and appreciated.
Cheers!
EDIT
Hi. Thanks everyone for your answers. My initial question -at least in my head- was not related to "Possible duplicate" suggested by Viktor Chvátal - but this question he pointed at, ALONG WITH all the other answers to my question clarified and dissipated my doubt. At the beginning, I though that if child does not implement the virtual method from parent, there would be some sort of "hole" there, where a method (or pointer to method, or whatever) should be. But then what would happen is that the child would be using the parent's implementation.
Thanks everyone and sorry for the fuss of asking something which is apparently already answered somewhere else. The thing is I should read more about how stuff works, before giving somebody else's comments as granted - wich is what took me to ask this question in the first place.
I'll try no to repeat this mistake in the future.
That is not the correct question to be asking. The correct question is if the child class only overrides one or two of the functions it is allowed to override then the question is "Should my child class be deriving from the parent class". For example of a bad inheritance is:
class shape
{
public:
virtual void draw();
virtual void print();
};
class log : public shape
{
public:
void print() override;
};
This is a bad inheritance as the two both need a print method but a log class has nothing to do with drawing nor is it related to a shape. Is it dangerous not in the context of security but in the sense that anyone using your code will be extremely confused it is.
An example of a better inheritance would be:
class shape
{
public:
virtual void draw() = 0;
};
class rectangle : public shape
{
virtual void draw();
};
Here square inherits from shape as a rectangle is a shape and the inheritance enforces rectangle to define a draw method. With this inheritance it is very clear as to what is going on and there is no risk involved.
Some children implements both virtual functions of their parent, but
some others implement only one
That is perfectly fine, and that's one of the reasons virtual methods differ from abstract ones, former being optional to be overridden in more specific types (child classes).
I know I can implement the methods, and when they are not needed they
could simply return an exception, or simply do nothing
Throwing exception, say not implemeted or supported, is bad idea. If you knew the specific type would not support specific behavior, that behavior should not be part of base class itself. You should implement such behaviors (which are specific to some derived classes) using interfaces instead.
You might be confusing virtual methods with pure virtual methods.
A virtual method is just a regular method that children classes can override, which means "swap the default behavior for a custom one".
You declare them like this:
virtual ReturnType myVirtualMethod();
Pure virtual methods, on the other hand require you to implement them in the child class. They are used when no sensible default behavior can be written within the parent class. In case you don't implement them, the child class will fail to compile, which is good, because it prevents undefined behavior - in this case: what should run when NO method was provided? It is impossible for the compiler to decide.
They can be declared with this syntax:
virtual ReturnType myVirtualMethod() = 0; // notice the "= 0" at the end
So I think the question you should ask yourself is this one: "can I provide any default behavior that works in most cases for this method?" If not, you should consider making the method pure virtual, otherwise implement the default behavior in the parent class, and don't bother overriding that method in child classes that don't need it.
Hope this helped!

Interface vs Implementation in C++. What does this mean? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am learning the concepts of inheritance, especially about access-specifiers, here I am confused about the protected access specifier. The members under protected can be accessible by the base class member functions and derived class member functions. There is a chance of messing up implementation of base class if we declare protected as access specifier. Its always better to declare data members under private rather than protected as only the interface is exposed and not the implementation section. We are declaring only the variables in the private section of a class and how it becomes implementation? Implementation will be done in the member functions right? The terms are confusing, can anyone clarify and explain me the terms?
Interface and implementation are not ideas specific to C++ and it sounds like you're confused about what interfaces vs. implementations are in general, so hopefully by explaining what they are it will be easier to understand it in C++.
This SO question (though not exactly what you're asking) has a good definition for what an interface is:
An interface is a contract: the guy writing the interface says, "hey, I accept things looking that way", and the guy using the interface says "Ok, the class I write looks that way".
An interface is an empty shell, there are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.
And in his example the interface is (translated to C++):
class MotorVehicle
{
public:
virtual void run() const = 0;
virtual int getFuel() const = 0;
}
And then the implementation is:
class Car : public MotorVehicle
{
int fuel;
public:
void run() const override
{
printf("Wrroooooooom\n");
}
int getFuel() const override
{
return this->fuel;
}
}
The implementation is the actual substance behind the idea, the actual definition of how the interface will do what we expect it to. Another example: in terms of algorithms we talk about a Depth First Search (DFS) and it has a clearly defined behavior, but how we code, or implement, that algorithm can vary. We could use recursion or a stack data structure, for instance.
Now as regards access specifiers: it is not bad to use protected access. We talk about inheritance as an "is-a" relationship. When we say Cat inherits from Animal, we also say Cat is an Animal. So for the Cat to use some of the instance variables of the Animal is perfectly normal because it should belong to the Cat anyway.
You're worried that something the subclass does will mess up what the superclass does by changing the instance variables. You can certainly do that by throwing in meaningless data from the subclass, but usually you don't do that. You use the instance variables as the superclass intended them to be used (otherwise you would indeed screw up the functionality), which should be documented. If you are still thinking that someone should really not use your instance variables then that's what the private specifier is for.
One last thing: overriding superclass methods should also prevent misuse of superclass variables. By accessing and writing to protected variables you might change the behavior of superclass methods to something undesired, but then those methods should be overridden to do the new thing that your subclass is intending to do.

declaring object of a class having all virtual functions [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Actually, it's my final term exam question.
Which of the following will create a compile time error?
Declaring object of a concrete class in the definition of main function.
Writing output statement, in constructor statement.
Declaring object of a class having at least one virtual function.
Declaring objects of a class having all virtual functions.
I've chosen 4th one. But still confused. Need help!
Some questions might be interpretable differently, so I will sum those up here. Note however, that some of these interpretations are not actually synonymes, but just my thoughts on what your teacher could have meant to say.
1. Declaring object of a concrete class in the definition of main function.
See this question: What is the difference between a concrete class and an abstract class?.
This shows it is valid to instantiate or declare a concrete class. The main function is no special exception to this.
Conclusion: this is valid.
2. Writing output statement, in constructor statement.
By constructor statement, I assume the constructor function of a class or struct, or something alike, is meant. Usually, I would say that an output statement is something like writing to the console. However, as the questions use kind of weird language anyway, one could say that by output statement the return statement is meant.
Output, as in writing to the console for example, is perfectly legal in a constructor function.
class Foo
{
public:
Foo()
{
std::cout << "I made a Foo\n";
}
}
Output, as in returning something from a function, is not legal in a constructor.
class Foo
{
public:
Foo()
{
return 3; // not legal
}
}
Conclusion: If this is valid or not depends on how you interpret the question.
3. Declaring object of a class having at least one virtual function.
Virtual functions in classes are explained here: C++ Virtual/Pure Virtual Explained.
The question is clear in that the one or more virtual function are not pure virtual, so:
Conclusion: this is valid.
4. Declaring objects of a class having all virtual functions.
See my explanation of answer 3 for an explanation of virtual and pure virtual functions.
The straightforward interpretation of this answer is: Is it legal to declare an object of a class of which all functions are virtual? In this case the statement is valid, see answer 3.
However, you could interpret all virtual functions as pure virtual functions, in which case instantiating the class is not valid.
Conclusion: If this is valid or not depends on how you interpret the question.
Final conclusion
Answer 1 and 3 both describe valid C++. However, answer 2 and 4 can be interpreted in multiple ways, so the answer is not clear.
Personal thought
I have never ever heard of someone calling a return statement an output statement. Neither have I heard of someone calling a pure virtual function an all virtual function. I think your teacher is weird.
None of the four options
Declaring object of a concrete class in the definition of main function.
Writing output statement, in constructor statement.
Declaring object of a class having at least one virtual function.
Declaring objects of a class having all virtual functions
would necessarily give a compilation error.
Any of them would give a compilation error if you include a syntax error, say.
However, it's unclear what the author means by "constructor statement", that's not a standard term.
It's possible that by "all virtual functions" the author means "one or more pure virtual functions". If so then then that's probably the intended answer.

What does `= 0` mean in the decalartion of a pure virtual function? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
C++ Virtual/Pure Virtual Explained
What's the difference between virtual function instantiations in c++
Why pure virtual function is initialized by 0?
This is a method in some class declaration that someone gave me. And I don't know what '..=0' means. What is it?
virtual void Print() const = 0;
The = 0 makes the function pure virtual, rendering the class an abstract class.
An abstract class basically is a kind of interface, which derived classes need to implement in order to be instantiable. However, there's much more to this, and it is some of the very basics of object-oriented programming in C++. If you don't know these, you need to go back to the textbook and read up. There's no way you can advance without understanding them.
That said, see this related question for some explanations of what virtual and pure virtual functions are. And as always, the C++ FAQ is an excellent resource for such questions.
It means that the virtual function is pure, meaning that you cannot call it as such: the function doesn't have any code to it, hence the = 0. Only by deriving the class and overriding the function you can call it. The class with pure virtual functions cannot be instantiated so they are called abstract classes, interfaces in some languages.
Basically, it means the function has no code. This means that you cannot use instances of this class. Rather, it can only be a base class.