C++ Logo

std-proposals

Advanced search

Re: [std-proposals] about incrementing a pointer of a type with pure virtual function

From: Henry Miller <hank_at_[hidden]>
Date: Fri, 20 Jan 2023 06:37:27 -0600
Opps, I meant A a[] = {&b1, &b2, &b3, &b4, &b5};

Obviously if a is uninitialized it is undefined behavior

-- 
  Henry Miller
  hank_at_[hidden]
On Fri, Jan 20, 2023, at 06:10, Henry Miller via Std-Proposals wrote:
> If you change main to
> int main(int, char**) {
> B b1, b2, b3, b4, b5;
> A a[5];
> f(a);
> }
>
> The program is well defined, and makes perfect sense. Granted it isn't 
> modern C++, and so not worth teaching (a criticism that applies to 
> whatever assigned caused the student to write that code in the first 
> place. ), but it is useful if you are writing C with classes. 
>
>
> -- 
>   Henry Miller
>   hank_at_[hidden]
>
> On Fri, Jan 20, 2023, at 00:55, Julien Allali via Std-Proposals wrote:
>> Hi everyone,
>>
>> I checked the following code from one of my student:
>>
>> class I{
>> public:
>>    virtual ~I(){}
>>    virtual void print(){
>>      printf("hello %p\n",this);
>>    }
>>    virtual void f()=0;
>> };
>>
>> class B : public virtual I{
>>    int i,j;
>> public:
>>    ~B(){}
>>    virtual void f(){
>>      printf("B %p\n",this);
>>    }
>> };
>>
>>
>> void f(I *i){
>>    for(int j=0;j<5;++j)
>>      {
>>        i->print();
>>        i->f();
>>        printf("i=%p ",i);
>>        i++; // PROBLEM IS HERE
>>        printf(" => %p \n",i);
>>      }
>> }
>>
>> int main(){
>>    B b[]={B(),B()};
>>    printf("B: %p %p\n",b,b+1);
>>    f(b);
>> }
>>
>> As you can see, I is a non instantiable type as it has one pure virtual 
>> method. My concern is about the line "i++": I believed it will lead to 
>> an error or at least a warning (g++ 11.3.0)... Indeed, I can not imagine 
>> a valid case where doing arithmetic on a pointer of a type with pure 
>> virtual function can be valid.... Shouldn't the standard forbid such 
>> arithmetic?
>>
>> Julien.
>> -- 
>> Std-Proposals mailing list
>> Std-Proposals_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
> -- 
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2023-01-20 12:37:48