Redefine Virtual Functions between header files in C++ - c++

I have one header file which uses a virtual function.
This is declared and defined:
#ifndef HeaderH
#define HeaderH
class Base {
<some code>
public:virtual int checkVal(int& val) { return val;}
};
#endif
I have another header file which declares some functions, and inherits from this base header.
Finally, I have the implementation of this header file in another .cpp file:
I want to override the virtual function checkVal in my implementation here, but I keep getting a redefinition error.
int Base::checkVal(int& value)
{
if(value == 0)
value = 10;
return value;
}
Is there something I should include in my header file which will override the Base virtual function?

You have already provided the definition of checkval() inside your base class, so why are you redefining it? You can define it only once.If you want to give the implementation inside the .cpp file, just declare checkval() inside the base class, no need to define it there.
Your implementation of checkval() fails if you call it like the following:
Base b;
//some code
b.checkval(10);//Error because temporaries cannot be bound to non-constant references
Is there something I should include in my header file which will override the Base virtual function?
Create a derived class inside the header file and override checkval() then by declaring the function inside the derived class and defining it inside .cpp file.

You have defined the function as { return val;} in the header file, you can't also define it as
{
if(value == 0)
value = 10;
return value;
}
anywhere else in your program. It can only have one definition. It may be that you meant the second definition to be for a derived class (and not Base), but that's not what you have in your code. The fact that your question doesn't use the word class at all tells me you might be confused about how virtual functions work. Read up on them some, it should be pretty obvious how to define a virtual function in a derived class.
It should look something like Derived::checkVal(int & value). note the use of "Derived" as the class name instead of "Base".

xxx.h
#ifndef HeaderH
#define HeaderH
class Base {
virtual int checkVal(int& val); // no definition
};
#endif
xxx.cpp
#include "xxx.h"
int Base::checkVal(int& value)
{
if (value == 0)
value = 10;
return value;
}
And it works fine. Else the compiler will not know what definition to use. There can be only one!

I don't think you mean overriding. And your implementation is missing a return type - it should be:
int Base::checkVal(int& value)

You have two implementations in your Base class, one in the header file, the other in the .cpp file. Just omit the one in the header file.

The error is exactly what you should get.
Without creating a new class that inherits from Base, you cannot redefine the function.
#ifndef DERIVED_H
#define DERIVED_H
#include "base.h"
class Derived : public Base{
<some code>
public:
virtual int checkVal(int& val)
{
if(value == 0)
value = 10;
return value;
}
};
#endif DERIVED_H
Then use Derived where you were going to use Base.
Please read Friendship and Inheritance.

Related

What does "class example;" mean in a Header File?

I've a question about something what really confuses me!
Let's watch this code righ here:
#ifndef HEADER_H
#define HEADER_H
#include <iostream>
class example;
class anything_else;
class A {
public:
A();
};
...
What does class example; and class anything_else; mean,
while class A {}; gets declared? Inside the CPP File i saw definitions like void example::release() { ... } and so on...
I'm really confused, does anyone have a example with class example; ... ?
What does class example; and class anything_else; mean
They are declarations of the classes example and anything_else. They tell the compiler that those are valid class names. This kind of declaration is informally referred to as "forward declaration".
while class A {}; gets declared?
class A gets defined.
Inside the CPP File i saw definitions like void example::release() { ... } and so on...
That's the definition of the function example::release.
Somewhere in the definition of example, there's the declaration of the function:
class example
{
// ...
void release(); // declaration
};
If example is only declared and not defined, then the definition of example::release results in a compilation error.
if you want to have member variables of a type that have not yet been included you do a forward declaration of the type.
class X;
forward declares the class X so you can have a. e.g. a pointer to that class in our class declaration.
class Y
{
...
X* p;
};
later you must supply the definition of the class somewhere in your .cpp file.

is there a way to skip class name while define a class member function in c++?

for example, I declare a class named Dog in the dog.h:
class Dog {
public:
void bark();
private:
int count;
}
Is there any way that I could just write the following code in the dog.cpp:
void bark() {
printf("count: %d", count);
}
instead of:
void Dog::bark() {
printf("count: %d", count);
}
It will help saving time if I got a ton of class functions which should be defined. (I can just copy-paste the function definition to .h file without the routine to delete class name every time.)
in the objective-c code, I can add a "#implementation ... #end" scope in the .m(its role is like .cpp) file, then I can just write the function like this:
in dog.h:
- (void) bark;
in dog.m:
#implementation Dog
- (void) bark {
printf("count: %d", count);
}
#end
So I think maybe there is a similar way in c++.
You see, I can copy the function definition codes in .m file to the .h file, and just need to add a ";" symbol in the line end. I even needn't to declare it in the .h file, if the class function is a private one. So I think objective-c is more convenient than c++ when declaring a class.
Is there any way that I could just write the following code in the dog.cpp?
No, you cannot do that. You must use the class name when defining member functions outside the class definition.
From the C++11 Standard:
9.3 Member functions
5 If the definition of a member function is lexically outside its class definition, the member function name shall be qualified by its class name using the :: operator.
Simple pattern
In your cpp file you may use the following pattern:
#include "dog.h"
#define _C Dog::
void _C bark () {
...
}
void _C foo () {
...
}
#undef _C
The use of the macro _C will be the same for any TU.
More elaborative pattern
Concept: generate code of member implementations straight in the class definition.
The pattern of file structure:
the regular header file named dog.h
the header file with method implementations to be
included, named "dog.hxx"
the cpp file including "dog.h" while the special macro IMPLEMENT_API defined
The regular header file dog.h:
class Dog {
public:
void bark();
private:
int count;
#ifdef IMPLEMENT_API
#include "dog.hxx"
#endif
}
The dog.hxx file:
void bark() {
printf("count: %d", count);
}
void foo() {
printf("foo: %d", count+1);
}
The dog.cpp file:
#define IMPLEMENT_API
#include "dog.h"
In a more complex case, one TU may be used for several instances of the second pattern like in the animals.cpp file below.
The animals.cpp file:
#define IMPLEMENT_API
#include "cat.h"
#include "dog.h"
Another class cat is defined as dog using similar statements with the IMPLEMENT_API macro.
In another file including dog.h or cat.h, only declarations will be generated because the IMPLEMENT_API macro must be defined only in a TU like dog.cpp or animals.cpp.
Pros: dog.hxx or cat.hxx files use contexts and namespaces of their classes allowing to omit the fully qualified name of a class for each member definition.
Caution: if a compiler does not allow to have a member declaration and a member definition at the same time, member declarations should be wrapped with the pattern #ifdef IMPLEMENT_API <member definitions> #else <member declarations> #endif.
Sorry for being late. I don't get around much. ;)
You don't need a .cpp file to define your function. You can do it in the class definition. In fact, you must do this if you want it in-lined.
Most people seem to have a .cpp fetish. ;) I put almost all my function in the class definition. Most of my classes don't have a .cpp file, but sometimes they are necessary.
voila! No Dog:: and no .cpp file either.enter code hereclass Dog {
public:
void bark() {
printf("count: %d", count);
}
private:
int count;
}
mark the function as friend in a class
class Dog {
friend void bark (Dog &); /// mark as friend
private:
int count = 22;
};
with this you can access some private members in a class Dog
void bark (Dog &d1)
{
std::cout << d1.count << std::endl;
}

Multiple definition of base class constructor?

I'm creating some classes to encapsulate socket IO. I've created a base class to abstract out common data (file descriptors, port #s, etc) and functionality (most of the initialization). I have code that looks like this -
base.hpp
class Base {
protected:
Base(int port);
~Base();
// common data
};
Also here I have the implementations of the constructor and destructor
client.hpp
#include base.hpp
class Client : private Base {
// constructor and other required code
}
testclient.cpp
#include "client.cpp"
int main() {
Client c (ip, port);
... more stuff
return 0;
}
I also have the implementation of the client class in client.cpp, and its constructor calls the base constructor appropriately. I also have correct and unique header guards. However, when linking client.o with testclient, I get linker errors citing multiple definitions of the Base constructor and destructor. What am I doing wrong? I would include the code, but it is quite long and I am convinced my error is due to some #include/linking magic.
If the functions are implemented in the header file you have to declare the definitions of the functions with inline to prevent having multiple definitions of the functions.
To fix the errors put inline in front of the implementations. For example for the constructor of Base do
inline Base::Base(int port)
^^^^^^ Difference here
{
// Implementation
}
You can also have the implementation of the methods in the class as well.
inline informs the compiler that the function can be compiled in multiple .cpp files (functions declared inside the class definition are implicitly declared inline.) If the function is not declared as inline it is exported from each .cpp file. When the linker comes along, after the program is compiled, there is a definition of the function in each .cpp file that included the header. This causes the linker to give an error.
Option 1:
In your header file client.hpp:
class Base {
protected:
Base(int port) {
...
}
~Base() {
...
}
};
Option 2:
In your header file client.hpp:
class Base {
protected:
Base(int port);
~Base();
};
And in your source file client.cpp:
Base::Base(int port) {
...
}
Base::~Base() {
...
}
#include base.hpp should be this #include "base.hpp"
or #include "base.h"

C++ method declaration, class definition problem

I have 2 classes: A and B. Some methods of class A need to use class B and the opposite(class B has methods that need to use class A).
So I have:
class A;
class B {
method1(A a) {
}
}
class A {
method1(B b) {
}
void foo() {
}
}
and everything works fine.
But when I try to call foo() of class A from B::method1 like this:
class B {
method1(A a) {
a.foo();
}
}
I get as result compile errors of forward declaration and use of incomplete type.
But why is this happening? (I have declared class A before using it?)
The compiler hasn't seen the definition of A at the point where you call A::foo(). You can't call a method for an incomplete type - i.e. a type for which the compiler doesn't yet know the definition of. You need to define the calling method after the compiler can see the definition of class A.
class A;
class B
{
public:
void method1(A a);
};
class A
{
public:
void method1(B b) { }
void foo() { }
};
void B::method1(A a)
{
a.foo();
}
In practice, you may want to place the definition for B::method1() in a separate cpp file, which has an #include for the header file containing class A.
C++ INCLUDE Rule : Use forward declaration when possible.
B only uses references or pointers to A. Use forward declaration then : you don't need to include . This will in turn speed a little bit the compilation.
B derives from A or B explicitely (or implicitely) uses objects of class A. You then need to include
Source: http://www-subatech.in2p3.fr/~photons/subatech/soft/carnac/CPP-INC-1.shtml
For avoiding multiple inclusion of header files you should include a guard, to prevent the compiler from reading the definitions more that once:
#ifndef EMCQUEUE_HH
#define EMCQUEUE_HH
// rest of header file ...
// definition code here...
#endif
See Industrial Strength C++ Chapter Two: Organizing the code.

interfaces, inheritance, and what between them

if i want to have 3 classes, which have common fields (and i want them to be static)
and they have a common function (which needed to be overridden, i.e virtual)
what the best design to do this?
do i need to create an interface in a header file
and then create it's .cpp file and get the 3 classes inheritance from it?
what about the static members?
can i declare them in the header file?
when creating header file which representing interface, do i have to create it's .cpp file?
Declare the classes in header files.
This is so that the declaration can be shared between multiple source files (with #include) and thus obey the (One definition rule).
It is traditional (though not required) that each class has its own file. To make it consistent and easy to find things you should name the file after the class. So Class A should be declared in A.h and defined in A.cpp.
MyInterface.h
class MyInterface
{
protected:
static int X;
static int Y;
static int Z;
public:
// If a class contains virtual functions then you should declare a vritual destructor.
// The compiler will warn you if you don't BUT it will not require it.
virtual ~MyInterface() {} // Here I have declared and defined the destructor in
// at the same time. It is common to put very simplistic
// definitions in the header file. But for clarity more
// complex definitions go in the header file. C++ programers
// dislike the Java everything in one file thing because it
// becomes hard to see the interface without looking at the
// documentaiton. By keeping only the declarations in the
// header it is very easy to read the interface.
virtual int doSomthing(int value) = 0; // Pure virtual
// Must be overridden in derived
};
A.h
#include "MyInterface.h"
class A: public MyInterface
{
public:
virtual int doSomthing(int value);
};
B.h
#include "MyInterface.h"
class B: public MyInterface
{
public:
virtual int doSomthing(int value);
};
C.h
#include "MyInterface.h"
class C: public MyInterface
{
public:
virtual int doSomthing(int value);
};
Now you define the implementation in the source files:
MyInterface.cpp
#include "MyInterface.h"
// Static members need a definition in a source file.
// This is the one copy that will be accessed. The header file just had the declaration.
int MyInterface::X = 5;
int MyInterface::Y = 6;
int MyInterface::Z = 7;
A.cpp
#include "A.h"
// Define all the methods of A in this file.
int A::doSomthing(int value)
{
// STUFF
}
B.cpp
#include "B.h"
int B::doSomthing(int value)
{
// STUFF
}
C.cpp
#include "C.h"
int C::doSomthing(int value)
{
// STUFF
}
There is no explicit "interface" thing in the C++ language.
If you'd like to have an interface-like class, that's a class with pure virtual methods (that is a method w/o definition, e.g. virtual void printme() = 0;).
Static variables are bound to object files (internal linkage). If you define them in your header file and include that header file into several cpp files, you'll end up having several definitions of that static variable (in different object files)
Since static variables are either global or part of a class, they cannot be 'common'. They belong to one class and may be accessed by another one.
Same goes for methods. One class has a method, another one may call it. If it's a derived class, it may also override it (that is either hide it or implement a virtual method).
Now, if you have three classes that have the same structure, you may (or may not) like to inherit them from a base class for several reasons. One is to avoid copying code. Another one is the main reason, that you may want to treat objects from the derived classes all the same, let's say you have a vehicle that you can use, but the vehicle may be a car, a bike or a plane. You want to use a vehicle, but don't mind which vehicle it actually is, so you create
class Vehicle
{
public:
virtual void use() = 0;
};
class Car
: public Vehicle
{
public:
virtual void use();
};
void Car::use()
{
// drive the car
}
Than you can use a Car as vehicle, for example
Car myCar;
Vehicle& myVehicle = static_cast< Vehicle& >(myCar);
myVehicle.use(); // drive the car.
That all is fundamental C++ OOP, look it up in some book.