Thread: Can you Initialize all classes once with New?

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    9

    Unhappy Can you Initialize all classes once with New?

    Greetings. I have a problem with the initialization of my classes I am new self taught C++ and need to understand how I can create a class with a pointer without any new operator, accept for one Initialization() function that initializes all the classes once with the new operator. I have tried this and searched google. When I simply use pointers after I initialize all the classes in one class, I get Access errors if another class tries to access it. The error states that the class/es are not initialized. Only the class with the initialization function can access it.

    The issue is that I have many classes. For example the ModelClass () . It will call the ArtItemClass() and take and remove art items. Then another Class, IslandClass() will also access the ArtItemClass() and will take and remove art items. The problem is after each class accesses the ArtItemClass() with a New operator the ArtItems’ set() and get() values as well as all the other specific values that each ArtItemsClass updates (current owner, current value etc…) is lost.

    Do I need to create static values for all of the classes that have values that must be maintained and updated, or can I create a pointer somehow so that only one instance of the class exists and can be altered and updated based on preserved values? I would not want to create all forty of my classes into singletons, if that is even an option. Thank you.


    here is the code I must place in each function before accessing the ArtItem() class:


    ArtItems* m_pArtItems;
    m_pArtItems = new ArtItems;

    m_pArtItems->SetNewLocation(4);


    Peace,

    Marcia

    I apologize I could not figure out the code tags

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Code?
    To use code tags, do:
    [code]my code in here;[/code]
    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
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    It sounds like the main problem is that you are confused about the concept of ownership and the lifetime of objects. There is also the hint that you are not clear of the difference between a class and an object.

    here is the code I must place in each function before accessing the ArtItem() class:
    That's the problem right there. Whenever a function is called, you create a new ArtItem object. However, from your description, it seems that you want your Model object to own a collection of ArtItem objects, or perhaps it has an association with, but not ownership of, a collection of ArtItem objects, with an Island object also having an association with this collection of ArtItem objects.

    If you want the former, then your Model object should have a std::vector<ArtItem> as a member. If you want the latter, then this vector should not be a member, but be independent of Model objects.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Nov 2007
    Posts
    9
    @ Laserlight. I appreciate your response, I feel nervous as I am a newbie and hope that I explained the problem fully; I did not mention that I use base classes.

    The problem may be in the creation of my classes. I have several base classes for example an ArtBase(), a PodBase(), an IslandBase(), a WarriorBase(). Then there are team classes that have the vectors to iterate through each base class. For example the PodTeam() iterates through the PodBase class. . If I understand what you are saying is that when I use

    Code:
    std::vector<ArtItem>
    The information is preserved? Would that be correct of the <PodBase*> class below.

    So in this code below all the PodBase information is retained as long as the initialization is like this std::vector<PodBase*> m_Pods; //here I am not creating a new PodBase Object?

    However Do I still have to do the “new” as you see in this function SpawnPod() below continuously for each function to access the classes it needs it seems redundant(it must be me ?

    Code:
    Model*  m_pModel = new Model;
    	PierTeam* m_pPierTeam = new PierTeam;

    Here is the full function where you can see that I have to use new to create access to needed classes. And the use of std::vector<PodBase*> Is this the proper protocol or can I initialize all the classes I need in one place so that I do not have to do this in each function?

    Code:
    //------------------------- SpawnPod ---------------------------------
    //this places the first angel pod on the island
    //PodTeam->PlaceFisrtPodsOnIsland(RegionManager->GetGameLevel());  
    //------------------------------------------------------------------------
    int PodTeam::SpawnPod(int regionLevel)
    {
    	Model*  m_pModel = new Model;
    	PierTeam* m_pPierTeam = new PierTeam;
    	int spawnedPod = 0;
     
     std::vector<PodBase*>  m_Pods;
    	if(m_pModel->GetGameLevel() == 1)
    
    	{
    		if(m_pPierTeam->IsTherePodAtPierLocation(100) == false )
    		{
    		
    		std::vector<PodBase*>::iterator it = m_Pods.begin();
    
    			for (it; it != m_Pods.end(); ++it)
    		  {
    
    		  if ((*it)->GetRegionLocation()== regionLevel  && (*it)->GetAliveStatus()== 1)
    		
    			  {
    	
    				(*it)->SetAliveStatus(2);
    
    				(*it)->SetPierLocation(100);
    				
    				spawnedPod = (*it)->PodESPR();
    				std::cout << "This is the Pod ESPR Gw!!!" << std::endl; 
    				std::cout << (*it)->PodESPR() << std::endl; 
    
    			}					
    		}
    
    	}
    
    }
    		std::cout << "Spawn Pod Number!!!" << std::endl; 
    		return spawnedPod; 
    		std::cout << spawnedPod << std::endl; 
    
    }
    Thank you for your response

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by peacerosetx View Post
    Code:
    std::vector<ArtItem>
    This is not right. If you try to place any other object than ArtItem in there, it would slice the object, if the code would compile at all.

    The information is preserved? Would that be correct of the <PodBase*> class below.
    If it's a pointer, then information will be preserved.
    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
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    I have several base classes for example an ArtBase(), a PodBase(), an IslandBase(), a WarriorBase(). Then there are team classes that have the vectors to iterate through each base class. For example the PodTeam() iterates through the PodBase class.
    When you say "base class", you mean "class that models a single object" rather than "class at the base of a hierarchy", right?

    So in this code below all the PodBase information is retained as long as the initialization is like this std::vector<PodBase*> m_Pods; //here I am not creating a new PodBase Object?
    It is true that you are not creating a new PodBase object. You are creating a new std::vector<PodBase*> that is local to the member function. If you have a member variable named m_Pods, that variable would be hidden by this local variable.

    And the use of std::vector<PodBase*> Is this the proper protocol or can I initialize all the classes I need in one place so that I do not have to do this in each function?
    I am guessing that m_Pods is a member variable. As such, you should initialise it in the PodTeam constructor. Also, since it is a vector of pointers, you would need to perform memory management, and thus delete each PodBase object in the PodTeam destructor, assuming that the PodTeam owns its PodBase objects (which is reasonable, in this case). Also, you should implement the copy constructor and copy assignment operator to do a deep copy, or declare them private and thus disable copying.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Nov 2007
    Posts
    9

    Question

    @LaserLight your help is very insightful your time is appreciated!

    When you say "base class", you mean "class that models a single object" rather than "class at the base of a hierarchy", right?
    Actually it is the bottom of the hierarchy, you put that nicely. What i mean is that the PodBase has the Pods Id number, their health points, the amount of time that they are alive, their reaction to warriors. The PodTeam() class is then able to group the PodBaseClass of pods through functions that have iterators. The PodTeam() can then access podsOnIsland(), or PodsAliveWithRedPoints(), PodsGoodHealth() etc.

    It is true that you are not creating a new PodBase object. You are creating a new std::vector<PodBase*> that is local to the member function. If you have a member variable named m_Pods, that variable would be hidden by this local variable.
    So for example in the example below when I change the SetAliveStatus(2); or the
    SetPierLocation(100); where (*it) is from the std::vector<PodBase*> (above), even if another function of this same PodTeam class creates another std::vector<PodBase*> m_Pods and accesses it with m_Pods the settings will be preserved from this earlier function since I am not creating a new PodBase object correct?

    Code:
    			(*it)->SetAliveStatus(2);
    
    				(*it)->SetPierLocation(100);
    I can’t understand why it is easy to access another class without the new with the std::vector, and why you can’t do this somehow with a regular object. When I do the compiler complains. If I write in the header for class Foo() as a private or protected member this code below:

    Code:
    Model*  m_pModel;

    And created the new to intialize it correclty. Then tried to access m_pModel to access their function in a class FooTwo() function I would get Access violation issues that I did not initialize the object correctly , even though another class initilized it for me already( I am from a Java background so I get confused with the naming convention of classes and object ..thank you for your patience)

    I saw a game where someone initialized all the classes once in an initialization and they were able to access each object with a pointer, I have been trying to find that example and can’t. Perhaps they were only accessing the classes for that particular class object and not for all the objects in their project. So am I correct that you must create the “new” class for each class that has functions that another Class’ function needs to access is that correct?

    @Elysia Thank you for your prompt response.
    Last edited by peacerosetx; 06-30-2008 at 01:38 PM.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Actually it is the bottom of the hierarchy, you put that nicely. If what you mean is that the PodBase has the Pods Id number, their health points, the amount of time that they are alive, their reaction to warriors.
    In that case, consider making PodBase an abstract base class. Only create objects of concrete classes that derive from PodBase.

    even if another function of this same PodTeam class creates another std::vector<PodBase*> m_Pods and accesses it with m_Pods the settings will be preserved from this earlier function since I am not creating a new PodBase object correct?
    No. In fact, m_Pods will be an empty vector. As I said, it is local to the function. As soon as control leaves the function, the vector is destroyed. In other words, you do not want to create this local variable at all. Rather, you want to initialise the member variable in the constructor, and destroy it in the destructor.

    And then tried to access m_pModel to access their function in a class Foo() function I would get Access violation issues that I did not initialize the object correctly
    Did you initialise m_pModel in the first place? For example:
    Code:
    class Foo
    {
    public:
        Foo()
        {
            m_pModel = new Model;
        }
    
        Foo(const Foo& other)
        {
            m_pModel = new Model(*other.m_pModel);
        }
    
        Foo& operator=(const Foo& other)
        {
            Foo temp(other);
            swap(temp);
            return *this;
        }
    
        ~Foo()
        {
            delete m_pModel;
        }
    
        void swap(Foo& other)
        {
            using std::swap;
            swap(m_pModel, other.m_pModel);
        }
    
        void bar()
        {
            m_pModel->func();
        }
    private:
        Model* m_pModel;
    };
    Of course, for the above code, I might not bother storing a pointer since I would be better off storing a Model object and thus not having to implement the copy constructor, copy assignment operator and destructor. If a pointer was needed, I might choose to use a std::tr1::shared_ptr for the same reason.
    Last edited by laserlight; 06-30-2008 at 01:47 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    std::shared_ptr? That one doesn't exist... yet.
    Some compilers have it in std::tr1::shared_ptr, I believe, but otherwise you can just get boost and use boost::shared_ptr.
    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
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    std::shared_ptr? That one doesn't exist... yet.
    Indeed, and fixed. (Might have to undo the fix in a few years.)
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Nov 2007
    Posts
    9
    No. In fact, m_Pods will be an empty vector. As I said, it is local to the function. As soon as control leaves the function, the vector is destroyed. In other words, you do not want to create this local variable at all. Rather, you want to initialise the member variable in the constructor, and destroy it in the destructor.

    But in the PodTeam Class there is a function which creates all the pods. In essence it goes through each pod and creates the new function to initiate it. This is done in the PodTeam constructor, and then it is destroyed in the destructor.

    I compiled it and it seemed to work, I need to do cout to see if it retains it value. As I have constructed it, the iterator in the PodTeam() class has the createPod() function in the constructor and this places them in the vector:


    This is how it is created. Are you saying that it is empty and the pods whose value I am changing in the SpawnPod() function won’t work?

    Code:
    //------------------------- CreateLevelOnePods ---------------------------------
    //			this creates the pods for the level  
    //------------------------------------------------------------------------
    
    void PodTeam::CreateLevelOnePods()
    {
    //PodBase m_pPodBase; /*->SetAngelPointsBalance(15);*/
    //m_pPodBase = new PodBase;
    
    
     m_Pods.push_back(new PodBase( 
    				1,//int	m_iPodESPR,
    				0,//int	m_iLifePath,
    				1,//int	m_iPodIDNumber,
    				1,//int	m_iRegionLocation,
    				0,//int	m_iIslandLocation,
    				0,//int	m_iPierLocation,
    				1,//int	m_iAliveStatus,
    				1,//int	m_iPodProfile,
    				0
    				/*WaitPod::Instance())*/));//int	m_iPodPointsBalance);
    
    
    
    etc with many more similar ones…


    What is intended to happen is that the PodTeam’s SpawnPod() function simply iterates this list for the next pod that is unborn so that it can spawn it.

    So say if you podA are not born, Once I find you as the (*it) in the ierator of SpawnPod(), I need you to change your setting from unborn to alive. What I need to make sure of is that as long as the pod’s settings are changed inside this function that it is retained after the control leaves the function. The bottom line is that the information of the PodA settings must be preserved. This way if this same function iterates five minutes later this podA can’t be instantiated again since it setting should have changed to alive, that is all I aim to do.

    This is the constructor and destructor that I have:

    Code:
    ////----------------------------- ctor -------------------------------------
    ////
    ////------------------------------------------------------------------------
    //
    PodTeam::PodTeam()
    
    {
    
    		
    
    	//PodTeam* m_pPodTeam = new PodTeam;
      //create the players and goalkeeper
      CreateLevelOnePods();
    }
    ////----------------------- dtor -------------------------------------------
    ////
    ////------------------------------------------------------------------------
    PodTeam::~PodTeam()
    {
      
      std::vector<PodBase*>::iterator it = m_Pods.begin();
      for (it; it != m_Pods.end(); ++it)
      {
        delete *it;
      }
    }

    Are you saying the way I have it set up will not work? Should I test with some couts or is this not going to work. This is my first C ++ program. Thank you for your help and guidance.

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    This is how it is created. Are you saying that it is empty and the pods whose value I am changing in the SpawnPod() function won’t work?
    Ah, this example is correct since you do not create a local variable, but use the member variable m_Pods.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Nov 2007
    Posts
    9
    @laserlight you have been a wonderful help God Bless you.

    @Elysia Appreciate you as well

    Peace

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  2. const arrays in classes.
    By anonytmouse in forum C++ Programming
    Replies: 6
    Last Post: 04-18-2004, 11:41 AM
  3. Exporting VC++ classes for use with VB
    By Helix in forum Windows Programming
    Replies: 2
    Last Post: 12-29-2003, 05:38 PM
  4. Prime Number Generator... Help !?!!
    By Halo in forum C++ Programming
    Replies: 9
    Last Post: 10-20-2003, 07:26 PM
  5. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 03:49 AM