Thread: public function returning const char * of private member

  1. #1
    Registered User
    Join Date
    Jun 2002

    public function returning const char * of private member


    I have a constructor, which calls a get member function. Unfortunatley, the get member function causes errors during run time.

    The get member function is entitled getLayerName() and returns a pointer to a constant character private data member. The return type is classified as const to prevent the user from altering the private data member.

    Function definition for getLayerName():

    const char * Layer::getLayerName()
    { return layerName; }
    Here is the declaration in the Layer.h header class file for layerName and getLayerName:

    const char * getLayerName();	
    char * layerName;
    Below is the constructor for the layer class, which calls the getLayerName() public function.
    The line with strcpy(buffer, getLayerName()) is giving me run time errors.

    //begin constructor
    Layer::Layer(char * fileName, char * wsDir)
    	setLayerType(fileName);			//from file extension
    	setDataSetType(fileName);		//from file name/layer type/univType
    	setLayerName(fileName);			//from file name/layer type/univType
    	setVisible(fileName);			//from univType
    	setId();						//auto updated		
    	setDataSetName(fileName);		//from file name
        setWorkSpaceDir(wsDir);			//given from invocation
    	char buffer[50];
    	strcpy(buffer, getLayerName());
    }	//end Layer::Layer constructor
    Why wont the strcpy function take the return from getLayerName() and copy it to buffer?
    " . . . and I lay awake, big dreamers never sleep." - David Lee Roth

  2. #2
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Cape Town
    Have you allocated memory for layerName?

  3. #3
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    The Dog has asked what I was going to say.

    You call the setLayerName(fileName); in your constructor, but
    are you allocating memory for layerName there? If not, that
    could be the error -- referencing a pointer that is mere garbage and no heap.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  3. Drawing Program
    By Max_Payne in forum C++ Programming
    Replies: 21
    Last Post: 12-21-2007, 05:34 PM
  4. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of
    Replies: 48
    Last Post: 05-10-2007, 02:25 AM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM