A derived array cannot be called a kind-of-base array. Let's understand this concept with the help of the following code:
snippet:
class parent
{
public: //1
virtual void a();
};
class child : public parent
{
public:
.....
private: //2
int n_;
};
void ABC(parent *arrayofparent)
{
arrayofparent[1].a(); //3
}
int main()
{
Derived arrayofChild[12]; //4
ABC (arrayofchild); //5
.....
}
In the preceding code snippet, the pointer declared to the derived class arrayOfChild has large size as compared to the pointer declared to the base class arrayOfParent class. The pointer arithmetic (which is used to keep adding 1 to a pointer to move from one value to the next) and the sizeof(Base) is used by the compiler internally when estimating the address for arrayOfParent[l]. Line 3 is incorrect because the sizeof operator is specific in terms of giving the size of array and pointer. The preceding code snippet will produce error-prone conditions.
The main problem of C++ is that it failed to differentiate between a pointer -to -an-array and a pointer-to-a-thing.
snippet:
class parent
{
public: //1
virtual void a();
};
class child : public parent
{
public:
.....
private: //2
int n_;
};
void ABC(parent *arrayofparent)
{
arrayofparent[1].a(); //3
}
int main()
{
Derived arrayofChild[12]; //4
ABC (arrayofchild); //5
.....
}
In the preceding code snippet, the pointer declared to the derived class arrayOfChild has large size as compared to the pointer declared to the base class arrayOfParent class. The pointer arithmetic (which is used to keep adding 1 to a pointer to move from one value to the next) and the sizeof(Base) is used by the compiler internally when estimating the address for arrayOfParent[l]. Line 3 is incorrect because the sizeof operator is specific in terms of giving the size of array and pointer. The preceding code snippet will produce error-prone conditions.
The main problem of C++ is that it failed to differentiate between a pointer -to -an-array and a pointer-to-a-thing.
No comments:
Post a Comment