简体   繁体   中英

C++ polymorphism, virtual functions error

I got the problem with virtual methods of my C++ projects.

First of all i got the class graphics which presents:

#pragma once
class gameGraphics
{
public:
    gameGraphics();
    ~gameGraphics();
    virtual void paint();
};

and i got two classes, first one :

class brick 
    : public gameGraphics
{
protected:
    int R, G, B;
    bool ifDelete;
public:
    brick();
    ~brick();
    virtual void paint(int x, int y);
};

And the second one:

class superBrick :
    public brick, public gameGraphics
{
private:
    int bonusType;
public:
    superBrick();
    ~superBrick();
    void paint(int x, int y);
};

Then im trying to paint objects of this two classes, when my projects runs it shows error: "Unhandled exception at 0x74D3CB49 in project.exe: 0xC0000005: Access violation executing location 0x00000000.", while trying paint function for superBrick object.

for (int i = 0; i < WIDTH; i++)
{
    for (int k = 0; k < LENGTH; k++)
    {
        temp = &table[k][i];
        temp->paint(k, i);
    }
}

I dont know what is the reason of this error, i think i did the Polymorphism good.

Sorry for my english, thanks for reading and help!

Have a good night!

EDIT:

class of table here:

class gameTable : public gameGraphics
{
private:
    brick** table;
public:
    gameTable();
    ~gameTable();
    void paint(int CordX, int cordY);   
};

I believe this is the source of your problem

    temp = &table[k][i];

You can't have polymorphism with an array of objects because they would all be of the same class.

You've omitted the definition of table but it probably should be an array of pointer that can reference different classes with the same parent class.

Access violation executing location 0x00000000 . This means you are dereferencing a null ptr ( a pointer of address 0. So the access violation is that you can't reference memory at location 0. Either table is null or table[k] is null. Make sure table is initialized with brick ptrs.

Also check "Cheers and hth" comments for good coding suggestions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM