C error c2079

C++ Documentation. Contribute to MicrosoftDocs/cpp-docs development by creating an account on GitHub.
description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2079

Compiler Error C2079

11/04/2016

C2079

C2079

ca58d6d5-eccd-40b7-ba14-c003223c5bc7

Compiler Error C2079

‘identifier’ uses undefined class/struct/union ‘name’

The specified identifier is an undefined class, structure, or union.

This error can be caused by initializing an anonymous union.

The following sample generates C2079:

// C2079.cpp
// compile with: /EHsc
#include <iostream>
int main() {
   std::ifstream g;   // C2079
}

Possible resolution:

// C2079b.cpp
// compile with: /EHsc
#include <fstream>
int main( ) {
   std::ifstream g;
}

C2079 can also occur if you attempt to declare an object on the stack of a type whose forward declaration is only in scope.

// C2079c.cpp
class A;

class B {
   A a;   // C2079
};

class A {};

Possible resolution:

// C2079d.cpp
// compile with: /c
class A;
class C {};

class B {
   A * a;
   C c;
};

class A {};

Think about the computer’s memory for a second here.

class B;

class A {
    byte aa;
    B ab;
};

class B {
    byte bb;
    A ba;
};

A x;

Now the question the compiler needs to answer is How much space should I reserve for x?

Let’s see. The first byte of x is byte aa;. Easy enough. That’s 1 byte.
Next comes B ab;. Let’s see what’s in there.
The first byte of x.ab is a byte bb;. That’s 2 bytes for x so far.
Next, is a A ba;. Let’s see what’s in there.
The first byte of x.ab.ba is a byte aa;. That’s 3 bytes for x so far.
And so on and so forth ad infinitum.
How big is x? The correct answer is of course *** OUT OF CHEESE ERROR ***.

The compiler doesn’t actually do this because it knows it can’t handle this case — so the syntax doesn’t allow circular containment in the first place.


Here’s a diagram of the contents of x in this example:
Diagram


UPDATE

Apparently, I forgot to include a solution here. Now that you understand what the problem is, the solution should be pretty simple. Use pointers. Either use a pointer from A to B and let B include A as it already does, or vice versa, or use two pointers. Then, you won’t have circular inclusion — if B doesn’t include a copy of A but just a pointer to it, that fixes the entire issue here.

  • Remove From My Forums
  • Question

  • Good Morning all,

    I encountered a compiler error c2079 which said «use of undefined class/struc/union name» and am not sure how to solve it. The following is a simplified setup of classes inside my code:

    class a;

    class b {

    int b1;

    public :

    func1();

    }

    b::func1()

    {

    a aclass;

    aclass.a1()     <== this is where error c2079 come from. a1 is a public function of class a

    }

    I search Microsoft C++ compiler error web. It suggests that using pointer to a, instead of instance of a. So I changed

    a aclass      to     a * aclass = NULL;

    and

    aclass.a1()     to     aclass->a1();

    The compiler error changed to c2027 : use of undefined type ‘a’

    Any suggestions? Thanks for your help.

    Tom Lin

Answers

  • I would suggest to split class interface (to be put in .h files) from class implementation (to be put in .cpp file).

    So, you should have 4 files: 

    ClassA.h (header containing interface of class A)

    ClassA.cpp (implementation of class A)

    ClassB.h (header containing interface of class B)

    ClassB.cpp (implementation of class B)

    The implementation of B::func1 method should be put in ClassB.cpp file.

    The implementation of A::a1 method should be put in ClassA.cpp file.

    At the beginning of ClassB.cpp file, you should add a #include «ClassA.h» because you are using class A.

    See if this helps…

    Giovanni

    • Marked as answer by

      Thursday, May 6, 2010 6:41 PM

  • Forum
  • General C++ Programming
  • error C2079: … uses undefined struct .

error C2079: … uses undefined struct …

Long code short:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Creature
{
    Creature(/*...*/) {}
};

struct Enemy : public Creature
{
    Enemy(/*...*/) : Creature(/*...*/)
}

class Combat
{
    Enemy enemy;
    Combat(/*...*/, Enemy enemy) : enemy(enemy) {}
}

class Game
{
    std::vector<Enemy> Enemies;
    Foo()
    {
        Enemy enemy(/*...*/)
        int rand = urand(0, Enemies.size()-1);
        Combat Combat(/*...*/, Enemies[rand])
    }
}

Gives an error:

error C2079: ‘Combat::enemy’ uses undefined struct ‘Enemy’

Where is the problem?

Which line?
You’re missing semicolons after the class declarations.

1
2
Which line?
You're missing semicolons after the class declarations. 

Hmm that was just a mockup. I fixed those semicolons and it seems problem wasnt there. Error was at line 13, Enemy enemy

Edit: I guess i’ll post whole thing when i get back to my computer

Last edited on

Are these in separate files?

Yes

Can you show which classes are in which headers and how each implementation #includes them?

Yeah. I’ve cut some parts a bit but it should do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#ifndef CREATURE_H
#define CREATURE_H

class Creature;

#include "include.h"
#include "spell.h"

class Creature
{
    //blah blah boring stuff here
public:
    Creature() {}
    ~Creature() {}

    Creature(int Atk, int Armor, int Health, int x, int y, int Level, std::string Name)
    {
        //...
    }
    Creature(int Atk, int Armor, int Health, int Level, std::string Name)
    {
        //...
    }
};

#endif 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#ifndef ENEMY_H
#define ENEMY_H

struct Enemy;

#include <SFMLGraphics.hpp>
#include "Include.h"
#include "item.h"
#include "player.h"
#include "creature.h"

struct Enemy : public Creature
{
    Enemy(int Atk, int Def, int Health, int x, int y, std::string Alive, std::string Combat, int Level, std::string Name);
    Enemy(int Atk, int Def, int Health, std::string Combat, int Level, std::string Name);
    ~Enemy();

    //...

    struct Loot
    {
        Loot(Item* Item, int Chance) : Item(Item), Chance(Chance) {}
        int Chance;
        Item* Item;
    };
    std::vector<Loot> Loot;
};

#endif 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#ifndef COMBAT_H
#define COMBAT_H

class Combat;

#include "game.h"
#include "enemy.h"
#include "spell.h"
#include "creature.h"

class Combat
{
    sf::RenderWindow &window;
    Player &player;
    Enemy enemy;
    //....
public:
    //...
    Combat(sf::RenderWindow &window, Player &player, Enemy enemy);
    int MainLoop();
};

#endif 
1
2
3
4
5
6
7
//Combat.cpp
#include "combat.h"

Combat::Combat(sf::RenderWindow &window, Player &player, Enemy enemy) : window(window), player(player), enemy(enemy)
{
    TextY = 510;
}
1
2
3
4
//Somewhere in game.cpp Combat object is created
Combat Combat(Window, player, *itr);
Combat.MainLoop();
//itr is std::vector<Enemy>::iterator 

Last edited on

I dont’ see it directly, but I’m willing to bet you have a circular inclusion problem. You appear to be just including all headers willy-nilly. Long story short, combat.h is including enemy.h, which is including some other header that includes enemy.h. The circular inclusion means that your Combat class is being defined before your Enemy class is.

Only include headers you need. See sections 4 and 5 of this article:

http://www.cplusplus.com/forum/articles/10627/#msg49679

Topic archived. No new replies allowed.

iRomul

160 / 101 / 14

Регистрация: 17.10.2012

Сообщений: 488

1

19.12.2015, 23:56. Показов 1223. Ответов 4

Метки c++, c2079, class (Все метки)


Приветствую. Ситуация следующая — есть 2 класса, оба используют друг друга. При компиляции вылезает ошибка:

Код

C2079 "MiniPlayer::music" использует неопределенный class "MiniMusic"

Файл MiniPlayer.h (класс MiniPlayer — синглтон)

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#pragma once
#include <string>
#include <vector>
#include <SFML/Audio.hpp>
#include "MiniMusic.h"
 
class MiniMusic;
 
enum Actions {
    AU_PLAY,
    AU_PAUSE,
    AU_STOP,
    AU_NEW_TRACK,
    AU_NEXT,
    AU_PREV
};
 
using FileVector = std::vector<std::string>;
using ActionCallback = std::add_pointer<void(Actions)>::type;
 
class MiniPlayer {
 
private:
    /* Audio files */
    FileVector files;
    FileVector::iterator currentPosition;
    /* Audio data */
    float volume;
    /* Action callback */
    ActionCallback callback;
 
protected:
    MiniPlayer() {
        files.reserve(10);
        currentPosition = files.begin();
        volume = 100.0;
        callback = nullptr;
    }
    ~MiniPlayer() { }
    /* Singleton dummy methods */
    MiniPlayer(MiniPlayer const&) = delete;
    MiniPlayer& operator=(MiniPlayer const&) = delete;
 
public:
    MiniMusic music; //<---------- Ошибка вылезает здесь
    static MiniPlayer& getInstance();
    FileVector& getFileList() { return files; }
    FileVector::iterator& getIterator() { return currentPosition; }
    int getCurrentIndex() { return currentPosition - files.begin(); }
    /* Music control methods */
    void setCallback(ActionCallback);
    void addAudio(FileVector files);
    void play(bool force);
    void play(bool force, int idx);
    void stop();
    void next();
    void prev();
    void vol(int);
    /* Music status methods */
    sf::Music::Status getStatus();
    /* Actions */
    void act(Actions a) const;
 
};

Файл MiniMusic.h

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#pragma once
#include <SFML/Audio.hpp>
#include "MiniPlayer.h"
 
class MiniPlayer;
 
class MiniMusic : public sf::Music {
    
    MiniPlayer* p;
    bool onGetData(sf::SoundStream::Chunk& data) override {
        return sf::Music::onGetData(data);
    }
 
public:
    MiniMusic() {
        p = nullptr;
    }
    bool setCallback(MiniPlayer& p) {
        this->p = &p;
    }
 
};

Что я упустил?
Спасибо.



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

19.12.2015, 23:56

Ответы с готовыми решениями:

Структура: error C2079: «A::myElem» использует неопределенный struct «A::B»
class A
{
public:
struct B;
private:
B myElem;
};

struct A::B
{

В зависимости от времени года «весна», «лето», «осень», «зима» определить погоду «тепло», «жарко», «холодно», «очень холодно»
В зависимости от времени года &quot;весна&quot;, &quot;лето&quot;, &quot;осень&quot;, &quot;зима&quot; определить погоду &quot;тепло&quot;,…

Исправить ошибку в строках «case 3:zadacha(Uch,Pr,Ocen);break;» и » return 0;»
#include&lt;stdio.h&gt;
#include&lt;stdlib.h&gt;
#include&lt;time.h&gt;
#include&lt;iostream.h&gt;
using…

Исправить ошибку:error C2678: бинарный «>>»: не найден оператор, принимающий левый операнд типа «std::istream»
Скажите пожалуйста, как исправить
error C2678: бинарный &quot;&gt;&gt;&quot;: не найден оператор, принимающий…

4

265 / 165 / 56

Регистрация: 25.02.2015

Сообщений: 435

20.12.2015, 00:01

2

странно. вроде нужный инклуд есть. попробуйте строчку 7 в миниплейере закоментировать.
ааа. у вас циклический инклуд получился. MiniMusic.h включает MiniPlayer.h и наоборот. Это надо устранить. Похоже что в MiniMusic.h не надо инклудить миниплеер. там форворд декларации достаточно.



1



335 / 183 / 80

Регистрация: 22.08.2013

Сообщений: 724

20.12.2015, 00:05

3

Цитата
Сообщение от iRomul
Посмотреть сообщение

MiniMusic music; //<———- Ошибка вылезает здесь

Замени на указатель, как сделал в MiniMusic.

Добавлено через 1 минуту
И это:

Цитата
Сообщение от Perfilov
Посмотреть сообщение

Похоже что в MiniMusic.h не надо инклудить миниплеер. там форворд декларации достаточно.



1



iRomul

160 / 101 / 14

Регистрация: 17.10.2012

Сообщений: 488

20.12.2015, 01:41

 [ТС]

4

Perfilov, nord_v, Благодарю, теперь заработало.

Добавлено через 11 минут
Рано порадовался — теперь в MiniMusic ругается на указатель — incomplete type. При чем даже есть добавить оба класса в один заголовок, то получится ошибка:

Код

C2027 использование неопределенного типа "MiniPlayer"

Выглядит это так:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class MiniPlayer;
 
class MiniMusic : public sf::Music {
 
    MiniPlayer* p;
    bool onGetData(sf::SoundStream::Chunk& data) override {
        bool res = sf::Music::onGetData(data);
        if (!res)
            p->next();
    }
 
public:
    MiniMusic() {
        p = nullptr;
    }
    bool setCallback(MiniPlayer& p) {
        this->p = &p;
    }
 
};
 
 
class MiniPlayer {
 
private:
    /* Audio files */
    FileVector files;
    FileVector::iterator currentPosition;
    /* Audio data */
    float volume;
    /* Action callback */
    ActionCallback callback;
 
protected:
    MiniPlayer() {
        files.reserve(10);
        currentPosition = files.begin();
        volume = 100.0;
        callback = nullptr;
    }
    ~MiniPlayer() { }
    /* Singleton dummy methods */
    MiniPlayer(MiniPlayer const&) = delete;
    MiniPlayer& operator=(MiniPlayer const&) = delete;
 
public:
    MiniMusic music;
    static MiniPlayer& getInstance();
    FileVector& getFileList() { return files; }
    FileVector::iterator& getIterator() { return currentPosition; }
    int getCurrentIndex() { return currentPosition - files.begin(); }
    /* Music control methods */
    void setCallback(ActionCallback);
    void addAudio(FileVector files);
    void play(bool force);
    void play(bool force, int idx);
    void stop();
    void next();
    void prev();
    void vol(int);
    /* Music status methods */
    sf::Music::Status getStatus();
    /* Actions */
    void act(Actions a) const;
 
};

Добавлено через 8 минут
Вроде как удалось решить, вынеся все реализации функций из MiniMusic.h в MiniMusic.cpp. При это в заголовке я не использую инклюд, но делаю форвард-декларацию, а в cpp файле уже инклюдю MiniPlayer.h.



0



335 / 183 / 80

Регистрация: 22.08.2013

Сообщений: 724

20.12.2015, 01:46

5

Цитата
Сообщение от iRomul
Посмотреть сообщение

bool onGetData(sf::SoundStream::Chunk& data) override {
bool res = sf::Music::onGetData(data);
if (!res)
p->next();
}

В классе оставь прототип, реализацию вниз кода убери.

Добавлено через 3 минуты
У тебя ошибка из-за этого была:

Цитата
Сообщение от iRomul
Посмотреть сообщение

p->next();

Тут, через указатель, вызывается метод класса MiniPlayer, а значит компилятор должен в этом месте видеть, что это за метод (форвард-декларации для этого недостаточно).



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

20.12.2015, 01:46

Помогаю со студенческими работами здесь

Error C2664: atoi: невозможно преобразовать параметр 1 из «_TCHAR *» в «const char *» Как исправить эту ошибку в коде?
#include &quot;stdafx.h&quot;

#define _XOPEN_SOURCE 500

#include &lt;conio.h&gt;
#include &lt;stdio.h&gt;…

Для каждой строки найти слова, которые не имеют ни одного из букв: «l», «k», «r», «s» i «j»
Задано символьные строки. Строка состоит из нескольких слов (наборов символов), которые разделяются…

Выдает ошибку «использована неинициализированная локальная переменная «flag» » и с переменной «sum_check» та же проблема
//func.cpp
#include&lt;iostream&gt;
using namespace std;

#include &quot;func.h&quot;

//Функция, которая…

Реализовать классы «Воин», «Пехотинец», «Винтовка», «Матрос», «Кортик» (наследование)
Разработать программу с использованием наследования классов, реализующую
классы:
− воин;…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

5

  • Remove From My Forums
  • Question

  • I am porting an application from VC6 to VS2015. when I am building after including all the header files I am getting the following error

    Error C2079 ‘IDBConnection’ uses undefined class ‘MIDBODBC::__MIDBODBC_EXPORT_MODE__’

    I have included the header file.. but still I get this.

    The class where IDBConnection is declared is like this:

    namespace MIDBODBC
    {

    class __MIDBODBC_EXPORT_MODE__ IDBConnection : public CObject
    {
    protected :
     CDatabase* m_pDBPtr;
     CMIPLOG  m_pLog;
     int   m_nDBConnectionIndex;
     int   m_nDBPoolWorkerIndex;

    …..

    …..

    }

    Can someone pl suggest how to tackle this error

    • Changed type

      Friday, January 31, 2020 3:56 PM
      Question

    • Moved by
      Xingyu ZhaoMicrosoft contingent staff
      Tuesday, February 4, 2020 1:29 AM

Понравилась статья? Поделить с друзьями:
  • C error 4996
  • C duplicate symbol error
  • C cin int error
  • C builder socket error
  • C builder error detected lme200