Thursday, June 07, 2012

Explicit & Implicit

Explicit & Implicit

Ira Pohl Contemporary C++ style is to use access specifies explicity rather than to rely on defaults. The use of implicit features is labor saving but error prone. Therefore, it is better style to declare point as follow:  

    Class point {
    Double x, y; //implicit
    Public:
    Void print() { cout << “” << end;;
    Class point {
    Private:
    Double x, y; //explicit


Explicit Constructors
The keyword explicit is used to create “nonconverting constructors”. 

    class MyClass {
    int i;
    public:
    explicit MyClass(int j) {i = j;}
    // ...
    };

Now, only constructors of the form

 MyClass ob(110);

will be allowed.
Otherwise if not, 

    class MyClass {
    int i;
    public:
    MyClass(int j) {i = j;}
    // ...
    };

Class objects can be declared as shown here:

 MyClass ob1(1);
 MyClass ob2 = 10;
In this case, the statement
 MyClass ob2 = 10;
is automatically converted into the form
 MyClass ob2(10)

If a method needs to refer explicitly to the object that evoked it, it
can use the this pointer. The this pointer is set to the address of the evoking object, so *this”
is an alias for the object itself. This is the location of object address for example.  

    class Animal {
    public String name;
    String talk(){return this.name;};
    String getName(){return name;};
    }

No comments: