[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 274
  • Last Modified:

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

0
rwniceing
Asked:
rwniceing
  • 5
  • 3
1 Solution
 
ZoppoCommented:
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
0
 
ZoppoCommented:
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
0
 
rwniceingAuthor Commented:
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
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
ZoppoCommented:
Question 1: The only possible difference between the two methods is whether the constructor is a inline function or not (as long as you don't use 'inline' explicit it's the choice of the compiler whether a function is inline or not).

In these two cases the constructor can be inline:
// declared and implemented within the class
class Circle
{
 ...
 Circle( double radius ) { m_radius = radius; }
};

// declared in a class, implemented outside of the class in the same file
class Circle
{
 ...
 Circle( double radius ) ;
};

Circle::Circle( double radius ) { m_radius = radius; }

Open in new window

So there's no difference between these two methods.

If you implement the function in another file than where it's declared it's (most probably) not possible to have it as an inline function:
// declared in a header file
class Circle
{
 ...
 Circle( double radius ) ;
};

// implemented in a cpp file
Circle::Circle( double radius )
{
  m_radius = radius;
}

Open in new window


About 2.: I meant there's no difference regarding the functionality. It's just common to keep the implementation outside of the classes in order to keep the class declaration clear and readable. Next the developer has to decide where to implement such functions. Usually small, fast functions are implemented in the header to allow them to be inline, larger, time consuming functions (where inlining has no significant effect) are implemented in a CPP file outside of the header. This usually is a good compromise between runtime-performance and compile-time.

For example with such a circle class it's a good idea to have the 'SetRadius' function within the class or at least within the header to allow it to be inlined because it's just a single assignment and calling it as a none-inline function is much overhead. But if you i.e. want to implement a function which determines whether to circles intersect and, if so, calculates the intersection points it's usually better to move it into a CPP file since such a function is much larger (needs more compile time when it's included in multiple other files) and the calling overhead used for none-inlined functions is most probably very small compared to the time the function needs to do its work.
0
 
rwniceingAuthor Commented:
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++?
0
 
ZoppoCommented:
: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
0
 
rwniceingAuthor Commented:
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
0
 
ZoppoCommented:
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
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now