Thread: Question about Constructors and Destructors with Pointers

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    4

    Question about Constructors and Destructors with Pointers

    Hello all,

    I am a new programmer and I am trying to look at how two classes can interact if one class is called by another. What I am trying to do is have a control class. This control class will then make a decision in the constructor about what "sub" classes to call (they are not inherited classes so not strictly a sub class). Since I don't know ahead of time which sub classes will be called I use a pointer in my class header file. In the constructor I then make a decision about the sub classes to call, instantiate the sub classes, and set the pointer to that sub class.

    Now here is the my problem; once the constructor finishes, the new sub class I made is destroyed. Later in the control class I have a function that uses the sub class pointer. The pointer works fine and all of the data is passed through the pointer and the function. My worry is that I am working off an artifact in the memory. Since the destructor is called on the sub class the pointer should be randomly pointing into space. Am I missing something about constructors/destructors and pointers? I am sure I am missing something, but I want to learn good technique and make sure I have easily modifiable code. Any help or insight is appreciated.

    Below is my test code:

    main file
    Code:
    #include "stdafx.h"
    
    using namespace std;
    int main()
    {
    	int kb = 0; // just a value to halt the program from closing the window
    	{ //  defining a new scope to test destruction and construction
    	int val_test = 5; // initialize the value val_test;
    	Class1 input(0); // call class one and initialize class one's variable
    	for (int ii = 0; ii < 10; ii++){ // loop to test this setup
    		cout << "my value: " << ii << endl;
    		input.set(ii); // resetting the values in class 1
    		}
    	}
    	cin >> kb; // just a halt command
    	return 0;
    	
    }
    my control class header and cpp files

    Code:
    #pragma once
    
    class Class2;
    class Class1
    {
    public:
    	Class1(int a); // constructor
    	~Class1(void); // destructor
    	void set(int a); // set function
    	int  & get(); // get function
    	friend class Class2; // make class two a friend
    private:
    	int b; // integer variable testing value passing
    	Class2 *Ptr; // pointer to second class that is called from this class
    };
    ,
    Code:
    #include "StdAfx.h"
    #include "Class1.h"
    using namespace std;
    Class1::Class1(int a)
    {
    	b = a; // initial assignment
    	Class2 sub_class; // creating a class2 object
    	Ptr = &sub_class; // setting a pointer to class2 object
    	cout << "constructor value of class1:   " << b << endl; // output statement to see the value was initialized
    }
    void Class1::set(int a)
    {
    	b = a; // set the integer value
    	cout << "Class1 stored value is:   " << b << endl; // out put the set interger value
    	cout << "Calling second sub_class" << endl; // calling the pointer to class2
    	Ptr->get(this); // pointer to second class passes the pointer of this object 
    }
    int &Class1::get()
    {
    
    	return b; // return a reference to this value
    }
    
    Class1::~Class1(void)
    {
    	cout << "my control class destructor is called" << endl; // tell me when the destructor is called
    }
    my sub class header and cpp files
    Code:
    #pragma once
    class Class1;
    class Class2
    {
    public:
    	Class2(void); // constructor
    	~Class2(void); // destructor
    	friend class Class1; // friending class 1 to see private data
    private:
    	int val; // value i want passed in from class1 object
    	int *valPtr; // pointer 
    	Class1 *Ptr; // pointer to class one object
    	void get(Class1 *cPtr); // get function to get value from class1 object
    };
    ,
    Code:
    #include "StdAfx.h"
    #include "Class2.h"
    using namespace std;
    Class2::Class2(void)
    {
    	val = 0;// initialize the value
    }
    
    void Class2::get(Class1 *cPtr)
    {
    	Ptr = cPtr; // set the pointer to class1 object
    	val = Ptr->get(); // calling the class1 function get to pass the data to class 2
    	cout << " Sub_class value is:   " << val << endl; // output what the data is
    }
    Class2::~Class2(void)
    {
    	cout << "my sub_class destructor is called" << endl; // telling me when this destructor is called
    }
    thanks again and I hope this is readable

    Specter

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Code:
    Class1::Class1(int a)
    {
    	b = a; // initial assignment
    	Class2 sub_class; // creating a class2 object
    	Ptr = &sub_class; // setting a pointer to class2 object
    	cout << "constructor value of class1:   " << b << endl; // output statement to see the value was initialized
    }
    Obviously, sub_class will be destroyed once the constructor ends because it's a local object. You'll have to use new if you want it to stay in memory until destroyed.
    There is your problem.

    Although, I haven't looked at your actual design due to lack of time, but this sounds like an unnecessary approach. You might consider using polymorphism a bit more.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by specter View Post
    Now here is the my problem; once the constructor finishes, the new sub class I made is destroyed. Later in the control class I have a function that uses the sub class pointer. The pointer works fine and all of the data is passed through the pointer and the function. My worry is that I am working off an artifact in the memory.
    Most likely.

    Since the destructor is called on the sub class the pointer should be randomly pointing into space.
    No. The pointer still points to the same place and that memory is not cleared, it is just freed for other use. So if it has not been used, it still contains the same thing.

    It is a very good idea to set a pointer to NULL after you delete or free the memory associated with it:
    Code:
    delete(ptr);
    ptr = NULL;
    This way you can test the pointer to see whether it is still valid. Otherwise, as you may notice, there is no way to tell if a pointer has been deallocated/freed already.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Mar 2010
    Posts
    4

    Thanks

    Thanks for all the assistance. I knew I had an issue there but since it was working I did not want to give myself a false belief that it was right. In answer to why I am doing it this way: I wanted to use inheritance but I need to do more than just inherit the variable names. I want to inherit the values too. Is there a way this can be done?

    Thanks,

    Specter

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    What do you mean by inherit values and names?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by specter View Post
    I want to inherit the values too.
    What values? A class inherits from another class, not an object (class instance initialized with values).
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    Mar 2010
    Posts
    4

    values and names

    My understanding of how inheritance works (please fix any bad knowledge I have): I can create a base class (point), and any derived class (circle). Circle will have access to the functions and variables in point. If I create two objects (circle my_circle) and (point my_point). They are different objects. my_circle will have the same variables and functions of object my_point but it won't share the same values. my_point may have a center at x = 0 and y = 0, but my_circle won't be able to know that my_point is at x = 0, y = 0 unless I explicitly pass those values from my_point to my_circle.

    I want a link between the my_circle object and the my_point object and I want them to share the values so that my_circle will know my_point is at x = 0 and y = 0. This way I don't have to pass large amounts of data or references.I know this goes against some of the data encapsulation that is really important, but for me it would save time and errors if I could form a direct link between the objects. I hope this makes sense.


    Thanks,

    Specter

  8. #8
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by specter View Post
    My understanding of how inheritance works (please fix any bad knowledge I have): I can create a base class (point), and any derived class (circle). Circle will have access to the functions and variables in point. If I create two objects (circle my_circle) and (point my_point). They are different objects. my_circle will have the same variables and functions of object my_point but it won't share the same values. my_point may have a center at x = 0 and y = 0, but my_circle won't be able to know that my_point is at x = 0, y = 0 unless I explicitly pass those values from my_point to my_circle.

    I want a link between the my_circle object and the my_point object and I want them to share the values so that my_circle will know my_point is at x = 0 and y = 0. This way I don't have to pass large amounts of data or references.I know this goes against some of the data encapsulation that is really important, but for me it would save time and errors if I could form a direct link between the objects. I hope this makes sense.


    Thanks,

    Specter
    Not really. my_circle inherits from Point, meaning there is a point object somewhere inside my_circle. It doesn't have a separate name. If you want to, say, initialize that part of my_circle with some other Point object, then you need to write a constructor that takes a Point object and use that to initialize the value of the point parts of your circle.

    EDIT: Or, if you want a bona fide point object, with its own name, inside your circle, you should be using composition, not inheritance.
    Last edited by tabstop; 04-01-2010 at 09:07 AM.

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by specter View Post
    I want a link between the my_circle object and the my_point object and I want them to share the values so that my_circle will know my_point is at x = 0 and y = 0. This way I don't have to pass large amounts of data or references.I know this goes against some of the data encapsulation that is really important, but for me it would save time and errors if I could form a direct link between the objects. I hope this makes sense.
    You seem to expect that two different objects somehow become linked together. That's obviously untrue for any object of any sort and type.
    If you need two places to share the same data, then create an object on the heap and make two pointers to point to it.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Create the point first and pass it in as a parameter to circle, and make it a member, eg:
    Code:
    class circle {
          point *p;
          circle (point *p) {  // circle constructor
                  this->p = p;
    Now you can write circle functions that access p's public members (eg, p->center).

    This is going to be problematic if point inherits from circle, however. You will need to use a separate base class common to both of them.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    That's what I'd call a nasty hack to do merely that.
    Circle should have a pointer to point only, and only if, Circle aggregates a pointer or if it's some internal implementation detail (but then it probably shouldn't be named pointer in the first place).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Elysia View Post
    That's what I'd call a nasty hack to do merely that.
    Oh malarky. That is standard programming. The class has member pointer to an external object, yay. It could be a string or a vector or anything else.

    Unless you like tying both hands behind your back and using your nose to write.
    Last edited by MK27; 04-01-2010 at 09:18 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  13. #13
    Registered User
    Join Date
    Mar 2010
    Posts
    4
    Elysia & MK27 you have both been really helpful in this situation. I know I have a weird setup but it allows me to keep everything away from the user and to keep things organized.


    Thanks for all of the help,


    Specter.

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by MK27 View Post
    Oh malarky. That is standard programming. The class has member pointer to an external object, yay. It could be a string or a vector or anything else.

    Unless you like tying both hands behind your back and using your nose to write.
    It's fine if it has a purpose, but it's just to bind point's members to circle, then it's a hack.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    838
    Quote Originally Posted by MK27 View Post
    there is no way to tell if a pointer has been deallocated/freed already.
    this is correct, however in debug mode, many compilers fill deleted memory with a specific value, such as 0xfeeefeee in VS x32, to tell you when using the debugger that a particular piece of memory has been deleted.

    since this is both compiler and compilation mode specific you should never program logic against this, but it can useful to know when trying to solve memory management bugs.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Constructors and Destructors
    By lasher in forum C++ Programming
    Replies: 2
    Last Post: 12-03-2006, 11:53 PM
  2. Destructors and Constructors on classes
    By Da-Nuka in forum C++ Programming
    Replies: 14
    Last Post: 06-14-2005, 02:08 PM
  3. Constructors and Destructors
    By GravtyKlz in forum C++ Programming
    Replies: 7
    Last Post: 03-09-2003, 10:44 AM
  4. Constructors And Destructors... What's The Point?
    By DeanDemon in forum C++ Programming
    Replies: 7
    Last Post: 12-15-2002, 12:47 PM
  5. Classes: constructors, destructors ???
    By mbeisser21 in forum C++ Programming
    Replies: 18
    Last Post: 07-21-2002, 09:33 PM