2

I'm creating a few classes and I decided to create a basic class that other classes will just inherit that basic class

So here is my basic class header

#pragma once

#include "ImageService.h"

class State
{
public:
    State( ImageService& is );
    ~State();

    void Update();

};

don't worry about the methods, they aren't the problem. So now I go ahead and create a IntroState like so (header file)

#pragma once

#include "State.h"

class IntroState : public State
{
public:
    IntroState(ImageService& imageService);
    ~IntroState();

    GameState objectState;
};

and here is the cpp file

#include "IntroState.h"


IntroState::IntroState(ImageService& imageService)
{
    //error here
}


IntroState::~IntroState()
{
}

at the constructor it is stating "no default constructor for class "State"", now what I think is going on is, the default constructor for State needs a imageService reference passed to it. So how would I pass the imageservice in this constructor to the state constructor?

Canvas
  • 5,779
  • 9
  • 55
  • 98

3 Answers3

8

Your base class has no default constructor, which is what gets implicitly called in your current derived class constructor. You need to explicitly call the base's constructor:

IntroState::IntroState(ImageService& imageService) : State(imageService)
{

}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
3

The usual way:

IntroState::IntroState(ImageService& imageService)
    : State(imageService)
{
}
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

You should call the constructor of State too, like this:

IntroState::IntroState(ImageService& imageService)
    : State(imageService) {
}

Tip: Don't use:

#pragma once, use guards!

Example:

#ifndef GRANDFATHER_H
#define GRANDFATHER_H

class A {
    int member;
};

#endif /* GRANDFATHER_H */

You can read more about the include guards in wikipedia.

You see #pragma is not standard. Neither became in C++11 (link).

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305