Is this virtual class defined in c++ standards?

A

Anarki

#include <iostream>
using namespace std;

virtual class Class {
public:
void fun() { cout << "Class::fun" << endl; }
};

int main() {
Class objClass;
cout << "Size of Class = " << sizeof(objClass) << endl;
cout << "Address of Class = " << &objClass << endl;
return 0;
}

normal size of class with no variables is 1 if there is a virtual
function size will be 4, but here the scenario is different its a
virtual class instead of virtual function. The program compiled
successfully in Visual Studio 2005. I expected a vptr to be inserted
in it. instead nothing like that. size of Class was 1 instead of 4. Is
this some kind of Undefined Behaviour?
 
N

Neelesh Bodas

#include <iostream>
using namespace std;

virtual class Class {
public:
void fun() { cout << "Class::fun" << endl; }

};

Std C++ doesnot allow "vitual" classes, it allows virtual functions
virtual inheritance.
 
N

Neelesh Bodas

#include <iostream>
using namespace std;

virtual class Class {
public:
void fun() { cout << "Class::fun" << endl; }

};

std C++ doesnot allow virtual classes.
It allows virtual functions and virtual inheritance.
 
R

Rolf Magnus

Anarki said:
#include <iostream>
using namespace std;

virtual class Class {

That's a syntax error. You can't make classes virtual.
public:
void fun() { cout << "Class::fun" << endl; }
};

int main() {
Class objClass;
cout << "Size of Class = " << sizeof(objClass) << endl;
cout << "Address of Class = " << &objClass << endl;
return 0;
}

normal size of class with no variables is 1

Actually, it's some implementation-defined value that must not be zero.
if there is a virtual function size will be 4,

Again, this is some implementation-defined value.
but here the scenario is different its a virtual class instead of virtual
function. The program compiled successfully in Visual Studio 2005.

Then you probably didn't run it in standard C++ mode.
 
K

Kai-Uwe Bux

Pete said:
Implementation-specific, but not implementation-defined.

I wonder, is it even guaranteed that there is a single value? or could
different classes all of which have no member variables have different
sizes?


Best

Kai-Uwe Bux
 
R

Rolf Magnus

IOW: It's unspecified.
I wonder, is it even guaranteed that there is a single value? or could
different classes all of which have no member variables have different
sizes?

They could all have different sizes. AFAICS, there is nothing in the C++
standard that forbids that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,291
Messages
2,571,476
Members
48,143
Latest member
Manuelevimb

Latest Threads

Top