calling ctor inside a member function of a class

Discussion in 'C' started by Frank Reich, Nov 29, 2006.

  1. Frank Reich

    Frank Reich New Member

    Joined:
    Nov 28, 2006
    Messages:
    15
    Likes Received:
    0
    Trophy Points:
    0
    Hello. May I ask a question to the ctor in this program.

    main.cpp:
    Code:
    #include <iostream>
    #include "cTest.h"
    
    int main()
    { 
    	cTest i;
    
    	i.SetA(5);
    
    	i.ClearA();
    
    	return 0;
    }
    cTest.h:
    Code:
    #pragma once
    
    class cTest
    {
    public:
    	cTest(void)
    	{itsA = 0;}
    	~cTest(void){}
    	void SetA (int i)
    	{itsA = i;}
    	void ClearA ()
    	{cTest();}
    private:
    	int itsA;
    };
    
    I am wondering, why the value of 'itsA' is not '0' after 'i.ClearA();' was called in main.cpp.

    Thanks.
    F.R.
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Its because when you are calling a constructor its creating a new object and assigning the value 0 and as the object goes out of scope its destroyed and so the object in the main does not reflect zero.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice