Implicit derived class in c++

I have no idea in this topic implicit derived class and implicit derived class object to base class object conversion. Please send me the explaination about this concept with simple example understandable by beginners. and also what is difference between ‘char * const ptr’ and ‘char const * ptr’ in c++
Last edited on
The difference between "char * const ptr" and "char const * ptr" is that the first one won't compile. "const char * ptr" would be the more readable way to type it though.
Ummmm... actually the first one will compile. It is a constant pointer to a char. The second one is a pointer to a constant char (normally a C-String, but could be anything). Here is an example:
1
2
3
4
5
6
7
8
9
10
11
12
int main() {
    char c1 = 'c';
    char c2 = 'C';

    char const* a = &c1; // pointer to const char (read backwards)
    a = &c2; // can assign
    // *a = 'd'  -- illegal, pointer to a constant char

    char* const b = &c1; // const pointer to char
    // b = &c2;  -- illegal, pointer is constant: cannot change it.
    *b = 'd'; // legal, not a pointer to a constant char
}


As for implicit conversion between derived class and base class, this is fairly logical. Look at it this way: A derived class contains all of the base class, as well as some 'bonus' extras. Hence, it can be have as the base class, as it will have all the functions given by the base class. This is how virtual functions work. Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

class Base {
    public:
        void func() { std::cout << "Base::func\n"; }
};

class Derived : public Base {
    public:
        void otherfunc() { std::cout << "Derived::otherfunc\n"; }
};

int main() {
    Derived* d = new Derived;
    d->otherfunc(); // Derived::otherfunc
    d->func(); // Base::func

    Base* b = new Base;
    b->func(); // Base::func
//  b->otherfunc(); -- syntax error, no otherfunc in Base

    Base* db = new Derived;
    db->func(); // Base::func
//  db->otherfunc(); -- syntax error, it doesn't know db is a Derived
}

When you get to virtual functions you'll understand how this is useful.
Last edited on
Topic archived. No new replies allowed.