call a destructor

This is a discussion on call a destructor within the C++ Programming forums, part of the General Programming Boards category; hi, i have this function that allocates memory for a char *temp. wanted to know if there is a way ...

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    75

    call a destructor

    hi, i have this function that allocates memory for a char *temp. wanted to know if there is a way to call the destructor every time i leave the function so that the space is deallocated. Or any other suggestions would do great.

    Code:
    const char* Microwave::status(void)
    {
    	temp=new char[80];
    
    
    	time(&end);//captures time again
    	
    	
    	 
                    difference=difftime(end,starts);
    	if(difference<seconds)
    	{
    		
    
    sprintf(temp,"Microwave in use. %.0f seconds left",seconds-difference);
    	    return temp;
    
    
    	}
    
    	//if difference is greater than the number of seconds, its off
    	//if seconds is 0 then its off
    	if(difference>seconds || seconds==0)
    	{
    		seconds=0;
    		sprintf(temp,"Microwave not in use");
    		return temp;
    	}
    	
    	//a default return incase none of the conditions are met
    	
    	return "";
    	          
    
    }
    
    Microwave::~Microwave()
    {
    	cout<<"called";
    	
    	delete[] temp;
    }

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,786
    Look up std::string

  3. #3
    Registered User
    Join Date
    Mar 2003
    Posts
    75
    I did look it up, but it doesnt call the destructor????

  4. #4
    Registered User codegirl's Avatar
    Join Date
    Jun 2003
    Posts
    76
    I think Fordy is suggesting that you use a string object instead of a char array...

    But since you declared your temp array in the function status, it's scope is only that function and the destructor can't access it, anyway. Just put the line to delete temp at the end of your status function..... oh wait a minute, you want to return temp.... um, I'm not sure what Fordy is getting at with the string class, but another way to do it would be to pass temp as a parameter to the status function:

    void Microwave::status(char *temp, int length)

    where length is the length of temp, if you need to know that... The pointer will act as a call by reference, if you've heard that term -- the temp pointer in status points to the char array in the calling function, so the status function can change the value of the char array and it will be changed in the calling function. I.E. status and the calling function are using the same array in memory, so of course changing it in one function changes it in another.
    My programs don't have bugs, they just develop random features.

  5. #5
    Registered User
    Join Date
    Mar 2003
    Posts
    75
    the thing is that these variables are declared in a .h file, and i have given you the .cpp of the .h file . So i cant pass the char as a parameter.

    .h file
    Code:
    //File: Microwave.h
    
    /* The purpose of the Microwave class is to abstract a simple Microwave. It provides
    functions to start the microwave, stop it and check the status of operations. It
    takes care of making sure that the microwave is not started when it still running. */
    
    
    #include<time.h>
    class Microwave
    {
    public:
    	Microwave();
    
    	~Microwave();
    
    	bool start(double);
    	//Purpose:To start the microwave.
    	//Requirement: In order for the microwave to start, it shouldnt be running already.
    	//Promise: To start the microwave for the number of seconds requested by the user.
    	//Exception: returns a true if all went well and microwave was started, else
    	//           returns a false if microwave is still running.
    	
    	void stop(void);
    	//Purpose: To stop the microwave
    	//Requirement:-
    	//Promise: Will stop the microwave.
    	//Exception:-
    	
    	const char* status(void);
    	//Purpose:Returns the current status of the microwave.
    	//Requirement:-
    	//Promise:- Returns "Microwave not in use" if microwave is not running.
    	//          Returns "Microwave in use. "Number of seconds" left where
    	//          Number of seconds is time left before microwave stops if
    	//          the microwave is still running.
    
    private:
    	
    	double seconds;//keeps the number of seconds inputted by user.
    
    	time_t starts;//captures time when microwave was started.
    
    	time_t end;//captures time when status is called.
    
    	char *temp;
    	           
    
    	double difference;//calculates the difference between starts and end in seconds
    					 //and is used to determine status.
    };
    .cpp file
    Code:
    //File: Microwave.cpp
    
    
    #include "Microwave.h"
    #include<time.h>
    #include<stdio.h>
    #include<iostream>
    using namespace std;
    
    Microwave::Microwave()
    {
    	seconds=0;
    	
    }
    
    bool Microwave::start(double set)
    {
    	//if seconds is not 0, that means it is running
    	//and thus false is returned
    	if(seconds!=0)return false;
    	
    	//else all things run and the microwave is started
    	else
    	{
    	seconds=set;
    	//time start is captured
    	time(&starts);
    	return true;
    	}
    
    
    }
    
    void Microwave::stop(void)
    {
    	//all is set to 0, indicating that microwave is off
    	seconds=0;
    	difference=0;
    
    }
    
    const char* Microwave::status(void)
    {
    	temp=new char[80];
    
    
    	time(&end);//captures time again
    	
    	
    	//calculates the difference in seconds, 
    	difference=difftime(end,starts);
    	//if difference is less than seconds its running
    	if(difference<seconds)
    	{
    		
    
    		//a static array to store the message returned
    		sprintf(temp,"Microwave in use. %.0f seconds left",seconds-difference);
    	    return temp;
    
    
    	}
    
    	//if difference is greater than the number of seconds, its off
    	//if seconds is 0 then its off
    	if(difference>seconds || seconds==0)
    	{
    		seconds=0;
    		sprintf(temp,"Microwave not in use");
    		return temp;
    	}
    	
    	//a default return incase none of the conditions are met
    	
    	return "";
    	          
    
    }
    
    Microwave::~Microwave()
    {
    	cout<<"called";
    	
    	delete[] temp;
    }
    the main file
    Code:
    // The output generated by this program should be:
    
    /*
    Started Microwave, response is success
    Microwave in use. 90 seconds left
    Microwave not in use
    Started Microwave, response is success
    Microwave in use. 20 seconds left
    Microwave not in use
    Started Microwave, response is success
    Microwave in use. 40 seconds left
    Started Microwave, response is failure
    */
    
    #include <iostream>
    #include <windows.h>
    #include "Microwave.h"
    
    using namespace std;
    
    void printStatus(Microwave& m)
    {
    	cout << m.status() << endl;
    }
    
    inline const char* printBool(bool result)
    {
    	return result ? "success" : "failure";
    }
    
    void main()
    {
    	Microwave aMicrowave;
    	bool result;
    
    	result = aMicrowave.start(90);
    	cout << "Started Microwave, response is " << printBool(result) << endl;
    	printStatus(aMicrowave);
    
    	Sleep(10000);
    	aMicrowave.stop();
    	printStatus(aMicrowave);
    
    	result = aMicrowave.start(30);
    	cout << "Started Microwave, response is " << printBool(result) << endl;
    	Sleep(10000);
    	printStatus(aMicrowave);
    
    	Sleep(21000);
    	printStatus(aMicrowave);
    
    	result = aMicrowave.start(40);
    	cout << "Started Microwave, response is " << printBool(result) << endl;
    	printStatus(aMicrowave);
    	Sleep(10000);
    
    	result = aMicrowave.start(10);
    	cout << "Started Microwave, response is " << printBool(result) << endl;
    }

  6. #6
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Code:
    void foo()
    {
       temp = new char[80];
       ...
       delete[] temp;
       temp = 0; // or... temp = NULL;
    }
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  7. #7
    Registered User codegirl's Avatar
    Join Date
    Jun 2003
    Posts
    76
    Well in that case, allocate the memory for temp in the constructor:

    temp = new char[80];

    Now temp will have the memory allocated until you delete it in the deconstructor. At the beginning of your status function, you can clear the current contents of temp if you want, but don't reallocate the memory because it's already allocated. Then when you're done with your microwave object, temp is deallocated in your destructor.
    My programs don't have bugs, they just develop random features.

  8. #8
    Registered User
    Join Date
    Mar 2003
    Posts
    75
    aah this way i wont have a major memory leak like i would have beore right?

  9. #9
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,786
    What I meant was to create a std::string and pass by value...

    That way you lose all the nastiness of having to mess with new/delete for a simple char array

    Code:
    #include <iostream>
    #include <string>
    
    std::string GetString()
    {
    	std::string foo;
    
    	foo = "Hello World";
    
    	return foo;
    }
    
    int main()
    {
    	std::cout << GetString();
    }
    Much simpler and easy to follow

  10. #10
    Registered User
    Join Date
    Mar 2003
    Posts
    75
    aah okay, i get what ur saying, but proff wanted us to use new/delete in the program to get a hang of things....and he also told us about checking memory leaks in the status function et al, he suggested programs like purify( too expensive), so I thought id ask you guys
    Last edited by kashifk; 07-16-2003 at 09:21 AM.

  11. #11
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,584
    You do not explicitly call a destructor, or a constructor for that matter. I guess you could say you call a constructor using new, but that's not really what is taking place.

    class Foo
    {
    public:
    Foo(void) {};
    ~Foo(void) {};
    }


    Foo *test=new Foo;

    This is not really calling the constructor from your code. The compiler creates the object and then calls the constructor function - although in asm I'm not sure if this is really a call or if it simply a compiler side action taking place.

    Likewise the compiler will call the destructor for your object when it is deleted or when the program exits. On exit all class destructors are called for those classes that are still alive or instantiated. If there is no destructor for that class, AFAIK the compiler provides an empty one similar to the one I've shown.
    So really constructors and destructors are implicit functions calls not to be explicity called by the programmer.

    In other OOP languages this is not true. Java has a garbage collector (which IMO is garbage) which sort of acts like a destructor but which the creators of Java warn that it is not exactly like a C destructor.

    But in C if you provide a destructor (and even if you don't) it will always be called upon object destruction. Very nice feature of C++ because you know exactly what is going on and when your object is going to be destroyed. IMO this is the best method of object creation/destruction, but again it's only my opinion.

    There are several people here which will probably disagree with me.

    I'm fairly sure my information is accuarate but just in case I'm sure there are some here who know exactly what is taking place in compiler side constructor and destructor calls.

  12. #12
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,786
    There should be a call instruction to both the destructor & the constructor.......but if either are empty then a good optimising compiler will skip the requirement

  13. #13
    Registered User
    Join Date
    Mar 2003
    Posts
    75
    im a n00b at c++ so please excuse the questions if they might seem too n00bish(lol):-
    so by allocating at the start of the program and deallocating at the end there wont be any memory leaks right????

  14. #14
    Registered User codegirl's Avatar
    Join Date
    Jun 2003
    Posts
    76
    As long as you deallocate everything you allocate, yes
    My programs don't have bugs, they just develop random features.

  15. #15
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Be sure to deallocate things exactly once, as well.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Call external C programs and receive data
    By ferenczi in forum C Programming
    Replies: 11
    Last Post: 02-12-2008, 11:32 AM
  2. howto add sys call using modules only ?
    By pinkeshzaveri in forum Linux Programming
    Replies: 1
    Last Post: 08-23-2005, 12:28 PM
  3. DirectMusic engine problem
    By VirtualAce in forum Game Programming
    Replies: 7
    Last Post: 03-17-2005, 05:12 PM
  4. Iterative Tree Traversal using a stack
    By BigDaddyDrew in forum C++ Programming
    Replies: 7
    Last Post: 03-10-2003, 04:44 PM
  5. call by reference and a call by value
    By IceCold in forum C Programming
    Replies: 4
    Last Post: 09-08-2001, 05:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21