C++ constructor differs from java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vinothg
    New Member
    • Oct 2006
    • 21

    C++ constructor differs from java

    Hi,

    I was just browsing some java code and found that it is possible in java to call a constructor within another constructor. The rule being that the it should be first line in the constructor and also there shouldn't be any duplication.Bot h these rules have valid reasons. But why can't we do the same in c++.

    Java Code :

    public class c {

    public c(){}
    public c(int a){
    this();
    }


    C++ code :

    class c{
    public :
    c(){}
    c(int a){
    this->c(); >>> Error
    }
    };
  • vinothg
    New Member
    • Oct 2006
    • 21

    #2
    Is it because "this" is a reference to the object in java and "this" is a pointer in c++

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Originally posted by vinothg
      Is it because "this" is a reference to the object in java and "this" is a pointer in c++
      In both languages 'this' is a pointer to the object itself. Java doesn't even know
      about references (although it (ab)uses the noun in several contexts). C++ has
      initialization lists following the colon in the ctor header. Not as elegant as the
      Java solution but doable; they're different languages you know.

      kind regards,

      Jos

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Originally posted by vinothg
        this->c(); >>> Error
        The this pointer can't be used to call a constructor inside the object constructor since this would set up an infinite recursion of calls.

        You can, of cource call any constructor inside a constructor provided these calls are not on the same object:
        [code=cpp]
        class c
        {
        public :
        c(){}
        c(int a)
        {
        //this->c(); //>>> Error
        c::c(); //OK. This is a different object
        }
        };
        [/code]

        Also, the function definition inisde the class is a Java thing. In C++ doing that makes the functions inline. Code your member functions outside the class.

        Comment

        Working...