Link to home
Start Free TrialLog in
Avatar of rwniceing
rwniceing

asked on

constructor defined in different way in C++

Dear Experts,

Attached code is a simple tutorial example C++ code for constructor  that I have understood it.
The constructor is just for initializing all Class's default parameter before any access, and I know
the Public label in the code that is allowed other external to access Class's stuff that is
different from Private label.

I have seen someone will do the constructor of Class in different ways such as the Method-2
and Method-3 in attached code which is now commented by " /*    */"

Question-1: What is different between Method-1 and Method-2 to declare the constructor inside
of  Class ?

Question-2 What is different between Method-3 and ( Method-1 and Method-2), at Method-3, it
declare the constructor outside(externally) of Class. Is it because it can allow other external class or
function access to the Class Circle ? But if it is already declared by Public label , why it still need to declare it outside or externally of Class Circle ?

Question-3, Sometimes,  "::" always seen , scope operator :: define a member of a class outside the class itself, So it means  Circle:Circle meaning other new  external  member call "Circle" is member of
Class Circle, Right ? If true, could I think it same way or  meaning on   std::cout  (using namespace std)   ?

Please advise

Rwniceing

#include<iostream>
using namespace std;
 class Circle //specify a class
{
    private : double radius; //class data members
    public:
        Circle() //default constructor
        {radius = 0;}
		/* Method-1 */
        Circle(double r) //parameterized constructor
        {radius = r;}
		/* Method-2
		Circle :: Circle(double r){radius = r; }
		*/
		/*Method-3 with external code
		Circle(double);
		*/
        Circle(Circle &t) //copy constructor
        {   radius = t.radius;}
        void setRadius(double r) //function to set data
        {radius = r;}
        double getArea()
        {return 3.14 * radius * radius;}
		~Circle() //destructor
        {} 
};
/*Method-3 with external code
Circle :: Circle(double r) { radius=r;}
*/
int main()
{
    Circle c1; //default constructor invoked
    Circle c2(2.5); //parmeterized constructor invoked
    Circle c3(c2); //copy constructor invoked
    cout << c1.getArea()<<endl; //0
    cout << c2.getArea()<<endl; //19.625
    cout << c3.getArea()<<endl; //19.625
    return 0;
}

Open in new window

Avatar of Zoppo
Zoppo
Flag of Germany image

Hi rwniceing,

about 1.: the comments already describe the kind of constructors:
- Circle() is a default contrustor which is needed to initialize default values some simple call like
     Circle c;
- Circle( double r ) is a specialized constructor which implements a convenient way to initialize values.
  For example it's easier/nicer to write
     Circle c(1.5);
  instead of
     Circle c;
     c.setRadius( 1.5 );
- Circle(Circle &t) is a copy constructor which copies values from a given instance to the new created one whenever one of these calls are used:
     Circle c1( c );
     Circle c2 = c;
 
about 2.: There's no (real) difference between implementing a function within a class where it's declared or to declare it in the class and implement it outside, i.e.:

  class X
  {
   void foo() { /*do something*/ } // declared and implemented at one place
   void bar(); // declared here, implemented outsied
  }

  void X::bar() // implementation
  { /*do something*/ }

It's common to implement (at least larger) functions outside of the class declaration to keep that declaration small. It's even very common to move the implementation out of the header i.e. into a .cpp because it saves compile time (exceptions are inline functions and templates, they need to be implemented within the file where they're declared).

about 3.: Whenever you need to 'tell' the compiler something (like i.e. a function or a static variable) belongs to a class which is declared elsewhere you need to prefix it with the class name scope (in your example the 'Circle::').

This is because it maybe another class even declares and implements a function 'Circle' so the compiler wouldn't know which function belongs to which class.

Hope that helps,

ZOPPO
Additional info about copy-constructor - as told it's called in two cases:

  Circle c;

  Circle c1( c ); // first case
  Circle c2 = c; // second case

There's a third case which looks quite similare to the second one:

   Circle c3;
   c3 = c;

That's a bit suprising because in this case the copy constructor is not called, instead the default constructor is called in the first line, in the second one a (maybe implicit generated) assignment operator is called.

From my experience it is a good practice to implement it somehow like this:

  class Circle
  {
   ...
    Circle& operator = ( const Circle& src ) // assignment operator
    {
      m_radius = src.m_radius;
      return *this;
    }
    Circle( const Circle& src ) { *this = src; } // copy constructor
  };

This has the advantages that all of the above shown cases call the same assignment operator and, i.e. if a new member is added it doesn't need to be handled twice in the copy constructor and the assignment operator.

ZOPPO
Avatar of rwniceing
rwniceing

ASKER

Question-1

I am asking

      /* Method-1 */
        Circle(double r) //parameterized constructor
        {radius = r;}
            /* Method-2
            Circle :: Circle(double r){radius = r; }
            */

Is method -1 no different from Mehtod-2 ?

Question-2,
Your answer is  no difference, besides compiler time, why programmer prefer to declare it externally? It seems it can be controlled easily, somehow in programming since the class may not in the same main file or they are in header file.

Please advise


Rwniceing
ASKER CERTIFIED SOLUTION
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
as I know inline as CSS style on tag such as <a style='font-size'></a> that is inline style which is not from CSS file

Zoppo,  what you mean, "inline" for C++?
:o)

Inlining in C++ means something quite different (in short):

After compiled a normal function is a chunk of machine code instructions somewhere in the memory. Whenever such a function is called from elsewhere a lot of things happen, i.e. CPU registers need to be saved before and restored after the function is called. In case the called function as in your sample only calls a simple assignment from one double to another this function calling overhead most probably takes more time than the assignment functionality itself.

Therefore C++ introduced inline function (http://en.wikipedia.org/wiki/Inline_function). If a function is inlined the compiler simply replaces the function call with the body of the function.

If i.e. you have a code like this:
 Circle c;
 c.SetRadius( 1.5 );

Open in new window

the compiler would treat it somehow like in this (pseudo-code) if Circle::SetRadius is not inlined
 c.Circle::Circle(); // Call the default constructor;
 c.Circle::SetRadius( 1.5 ); // call the function

Open in new window

But if the SetRadius is inlined it would do something like this:
 c.Circle::Circle(); // Call the default constructor;
 c.m_radius = 1.5; // use function's code inline

Open in new window

The latter one does usually consume much less CPU cycles since instead of two function calls only one function call is executed.

ZOPPO
Thanks for your detailed reply.

Last Optional question or advice.
I am doing  a lot, php, javascipt(jquery)  programming, but those are interpreted language for web browser. If we are going to develope some web application, I think node.js and javascript ,php is good enough . Java runtime installed on client server or user PC  can be replaced by node.js which is written in C++ and also browser javascript engine is also written in C++ such as chrome V8 engine  , so I don't know why Java programming is still existing if you can be familar with C, C++,C# with php, javascript, node.js, jquery, HTML5  and those code is  open source  ? the reason of java is still being used that I think it is history for java, a lot application is based on java  with its commercial proprietary.

So I guess I am going to go back or spend more time on C, C++ and C#  from tutorial and give up  java  programming which its source is NOT open  source to public. For example, you can find  a lot of most updated open source HTML5 javascript Game code but for java Game code is really outdated you can find on internet.

Please advise
You're welcome ...

About why Java is still used I think there are two main reasons:

1. There's IMO no other runtime which is implemented on such a wide spreaded hardware devices (beside computers with Linux, Windows, OSx it even runs on things like routers, smartphones, MP3 players, watches, in cars, lot's of more), there's nearly nothing which is any kind of computer where no JVM exists for so it's one of the most real platform independant languages.

2. It's an easy and clear designed OO language for beginners to learn object orientated programming without need to fight with C++ stuff like pointers, memory allocation, build chains (compiling and linking), maybe more, so it's often used for educational reasons.

To be honest I for myself don't really like Java allthough I know it's powerful and even has some neat features which aren't possible in C++ (because Java instead is some kind of mixed compiled and interpreted) I more like to work with C++ which nearly doesn't have any restrictions (i.e. I hate it lot's of Java classes are 'final' so it's not possible to derive from them).

But this is just my opinion ...

Best regards,

ZOPPO