0

Can you help me please with this problem? I have four classes. Honeypot header:

class Honeypot
{

public:
int getNumberOfInterfaces();
Honeypot (int numberOfInterfaces);
virtual std::string typeHoneypot()=0;
protected:
    int numberOfInterfaces;
};

Honeypot.cpp:

Honeypot::Honeypot(int numberOfInterfaces){
this-> numberOfInterfaces = numberOfInterfaces;
}

int Honeypot::getNumberOfInterfaces(){
return numberOfInterfaces;
}

Class Honeypot has child HoneypotV and HoneypotN. Now I created object with number of neteorkInterfaces:

Honeypot* NetworkType::createObject(int res1, int res2, int res3) {
    if (res1 == 1 && res2 == 1 && res3 == 1) {
    HoneypotV p1(3);
    return &p1;
} else {
    HoneypotN p2(3);
    return &p2;
}

In the main function:

NetworkType select;

Honeypot *p;

p = select.createObject(1,1,1);

cout << p->typeHoneypot() << endl;
cout << p-> getNumberOfInterfaces() << endl;

typeHoneypot() is correct, but getNumberOfInterfaces() returned value -858993460, correct is 3.

Thank you for reply.

Mato
  • 225
  • 1
  • 6
  • 10
  • 7
    You're dereferencing an uninitialized pointer. You're also returning the address of a variable that's gone out of scope. For the second, at least, there's the famous [Hotel Room response](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope). The former is discussed [in here](http://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-a-c-programmer-should-know-ab). – chris May 27 '13 at 20:39
  • 1
    You should not return a reference to a local object. http://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable – selalerer May 27 '13 at 20:43

2 Answers2

3

You returning a pointer to local variable, but when you exit from your function, all local variables will be destroyed and pointer will reference to already destroyed object

About code in main function: you declare a pointer to object and havent initialize it, so pointer points to some trash in memory

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Evgeny Eltishev
  • 593
  • 3
  • 18
1

You should dynamiclly instanciate the object if you want to return it :

Honeypot* NetworkType::createObject(int res1, int res2, int res3) {
    if (res1 == 1 && res2 == 1 && res3 == 1) {
    HoneypotV *p1 = new HoneypotV(3);
    return p1;
} else {
    HoneypotN *p2 = new HoneypotN(3);
    return p2;
}
rednaks
  • 1,982
  • 1
  • 17
  • 23