Edgar Buchvalov
Edgar Buchvalov

Reputation: 257

c++ class inheritance error C2509

i have two classes first: .h file

 #ifndef Vandenynas_H
#define Vandenynas_H
#include <cstdlib>
#include <iostream>
#include <string>
#include "skaicioti.h"
using namespace std;

class Vandenynas {
public:
    void danne (int i,int a, int a0);
    void getdan();
    string GetName ();
};
#endif  

.cppfile

  #include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include "Vandenynas.h"

skaicioti::v vektorV;
void Vandenynas::danne(int i,int a, int a0)
{ 
    switch (i)
    {
        case 0:
            vektorV.x=a-a0;
            break;
        case 1:
            vektorV.y=a-a0;
            break;
        default:
            vektorV.z=a-a0;
            break;
    }
}

second: .h file

    #ifndef Zuvis_H
#define Zuvis_H
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include "Vandenynas.h"
class Zuvis:public Vandenynas
{
public:
    void plaukti();
};
#endif  

.cpp file

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>

#include "Zuvis.h"
skaicioti::v vektorZ;
void Zuvis::plaukti()
{
    cout<<"plaukia\n";
}
void Zuvis::danne (int i,int a, int a0)
{
        switch (i)
    {
        case 0:
            vektorZ.x=a-a0;
            break;
        case 1:
            vektorZ.y=a-a0;
            break;
        default:
            vektorZ.z=a-a0;
            break;
    }
}

and when i compile i get error: zuvis.cpp(14) : error C2509: 'danne' : member function not declared in 'Zuvis' maybe someone can tell me where is my mistake?

Upvotes: 1

Views: 1387

Answers (1)

Vlad
Vlad

Reputation: 35594

I think you need the following:

  1. danne should be virtual,
  2. danne should be declared in the header of the class Zuvis.

class Vandenynas
{
public:
    virtual void danne (int i,int a, int a0);
    void getdan();
    string GetName ();
};

class Zuvis : public Vandenynas
{
public:
    void plaukti();
    virtual void danne (int i,int a, int a0);
};

The problem is that (1) if you don't declare danne as virtual in the base class, you won't be able to present alternative implementation in the derived class (that is, override it), and (2) if you are going to override the function in the derived class, you should say that already at the point of class declaration.

Alternately, you might want to just overload the function in the derived class. For that case, you don't need virtual in both cases (though you still need to declare the function in the Zuvis's header). That way your function hides the function with the same name in the base class, and doesn't override it.

The difference between hiding and overriding can be seen here:

Vandenynas* pv = new Zuvis();
pv -> danne(0, 0, 0); // (*)

The line marked (*) executes Vandenynas's implementation of danne in the case of hiding, and Zuvis's implementation in case of override. Do you see?

Upvotes: 4

Related Questions