hi
i have a class with a member which is a pointer to an object on the heap.
(the object is created from outside the class and is passed to it as a reference in the constructor).

when i try to access it from void functions, everything is ok.

but when i try to access it from value returning functions, i get a segmentation fault.
(the functions are public members of the class)

is it something i'm missing, or is just impossible? (to access from value returning funcs..)

class candidate{
private:
	...
        int id;
        myClock *clock;
	...

public:
	candidate (int _id, myClock &_clock ); //constructor
	int getID();
	void waiting();
};

candidate::candidate
		(int _id, myClock &_clock)
{
	id = _id;
	clock = &_clock;
	
}

int candidate::getID(){
	(*clock).some_method();  // <=this generates segfault
        return id;
}


void candidate::waiting(){
	 (*clock).some_method(); // <===== this doesnt
	
}

i dont understand why the myClock object is not visible from the getID() method.


thaks!

Recommended Answers

All 3 Replies

It's impossible to say with this example.

Where do you call waiting(), and where do you call getID()?
How do you make sure that the clock* is valid? Maybe the Clock object that you passed by ref. to the constructor has already 'died' when you call getID().

So better show us some more code (e.g. the shortest code necessary to reproduce the problem).

hey

this is where i call it from:

#include <everything needed>

int main(){

        myClock *c = new myClock();
	myClock &_clock = *c;
	candidate j (1 , _clock );

        int i=j.getId();
        j.waiting();
}

thats more or less what i'm trying to do

Why do you create the _clock in main? You can also just hand over *c to the j constructor.

Other than that we still need more precise info... Why don't you create a compilable example that has the same problem.

Right now you are giving us code that isn't the same as what you're running, so we have to guess what you are _really_ doing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.