Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you inherit from a class in a different header file?

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’
like image 898
Steven Oxley Avatar asked Oct 31 '08 12:10

Steven Oxley


People also ask

How do you derive a class from another class in C++?

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.

What is class header file C++?

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.

How do you access private members of inherited classes?

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.

What is the syntax for inheriting a 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.


1 Answers

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;
}
like image 198
Claudiu Avatar answered Nov 09 '22 09:11

Claudiu