I am having dependency troubles. I have two classes: Graphic
and Image
. Each one has its own .cpp and .h files. I am declaring them as the following:
Graphic.h
:
#include "Image.h"
class Image;
class Graphic {
...
};
Image.h
:
#include "Graphic.h"
class Graphic;
class Image : public Graphic {
...
};
When I try to compile, I get the following error:
Image.h:12: error: expected class-name before ‘{’ token
If I remove the forward declaration of Graphic
from Image.h
I get the following error:
Image.h:13: error: invalid use of incomplete type ‘struct Graphic’ Image.h:10: error: forward declaration of ‘struct Graphic’
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming. Inheritance is a feature or a process in which, new classes are created from the existing classes.
C++ classes (and often function prototypes) are normally split up into two files. The header file has the extension of . h and contains class definitions and functions. The implementation of the class goes into the . cpp file.
Private members of a base class can only be accessed by base member functions (not derived classes). So you have no rights not even a chance to do so :) Show activity on this post. Well, if you have access to base class, you can declare class B as friend class.
The ": public base_class_name" is the essential syntax of inheritance; the function of this syntax is that the class will contain all public and protected variables of the base class.
This worked for me:
Image.h:
#ifndef IMAGE_H
#define IMAGE_H
#include "Graphic.h"
class Image : public Graphic {
};
#endif
Graphic.h:
#ifndef GRAPHIC_H
#define GRAPHIC_H
#include "Image.h"
class Graphic {
};
#endif
The following code compiles with no error:
#include "Graphic.h"
int main()
{
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With