This question already has answers here:
Vectors and polymorphism in C++
(4 answers)
Closed 6 years ago.
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
class base {
int data;
public:
base(int d = 100) : data(d) {}
virtual int getData() const {return data;}
};
class derived : public base {
int dData;
public:
derived(int dd = 32) : base(), dData(dd) {}
virtual ~derived(){}
int getData() const {return dData;}
};
int main(){
std::vector<base> vec;
base A(20);
derived B(32);
vec.push_back(A);
vec.push_back(B);
for(unsigned int i=0; i < vec.size(); i++)
cout << "vector[" << i << "] :" << vec[i].getData() << endl;
base * ptr;
ptr = &A;
cout << "Base pointing: " << ptr->getData() << endl;
ptr = &B;
cout << "Derived pointing: " << ptr->getData() << endl;
}
Above the code,i create a vector which is type of base and put a derived object in it. when i try to read the values i cant get the correct ones. Even though i put 'virtual' statement before the function which has the same name in my classes. But in pointer way there is no problem.
here is the output of code.
vector[0] :20
vector[1] :100
Base pointing: 20
Derived pointing: 32
int main(){
std::vector<base *> vec;
base A(20);
derived B(32);
vec.push_back(&A);
vec.push_back(&B);
for(unsigned int i=0; i < vec.size(); i++)
cout << "vector[" << i << "] :" << vec[i]->getData() << endl;
base * ptr;
ptr = &A;
cout << "Base pointing: " << ptr->getData() << endl;
ptr = &B;
cout << "Derived pointing: " << ptr->getData() << endl;
}
Well, when i use pointer base vector, it gives the correct values. Thank you for your answers.
Related
This is my first ever question posted on Stack Overflow, hope someone could explain it.
So basically the two classes are the same except the order of the private member variables. The output is 10 20 10 0 I cannot understand why the order of declaration affects the output.
#include <iostream>
using namespace std;
class MyClass{
public:
MyClass(int value): b(value), a(b * 2){
cout << b << " " << a << " ";
}
private:
int b;
int a;
};
class YourClass{
public:
YourClass(int value): d(value), c(d * 2){
cout << d << " " << c << " ";
}
private:
int c;
int d;
};
int main(){
MyClass obj(10);
YourClass OBJ(10);
}
Class members are initialized in the order of their declaration.
Initialization Order of Class Data Members
#include <iostream>
class MyClass{
public:
MyClass(int value): b(value++), a(value++){
std::cout << b << " " << a << " " << std::endl;
}
private:
int b;
int a;
};
class YourClass{
public:
YourClass(int value): b(value++), a(value++){
std::cout << b << " " << a << " " << std::endl;
}
private:
int a;
int b;
};
int main(){
MyClass obj(10);
YourClass OBJ(10);
}
Output:
10 11
11 10
Consider the following C++ code:
#include <iostream>
using std::cout;
class A
{
public:
int a;
A():a(0)
{
cout << "A constructor\n";
}
virtual void f()
{
cout << "f inside A\n";
}
};
class C : public A
{
public:
int c;
virtual void f()
{
cout << "f inside C\n";
}
C():c(0)
{
cout << "C constructor\n";
}
};
int main()
{
A varA = C();
cout << "Size of C class: " << sizeof(C) << "\n";
cout << "Size of varA object: " << sizeof(varA) << "\n";
C* varC = static_cast<C*>(&varA);
varC->f();
cout << "varC->a is " << varC->a << "\n";
cout << "varC->c is " << varC->c << "\n";
}
The output of this program is:
A constructor
C constructor
Size of C class: 16
Size of varA object: 8
f inside A
varC->a is 0
varC->c is 1726166356
I initialize the varA object with the constructor of class C. Constructors of A and C class are called, but the varA is a simply a A object. I cast the address of varA to C* type and I try to call its f() function, but it prints the f() function of class A, so I deduce that it is use the early binding mechanism to call it.
I think if I call the constructor of derived class, like this case, I obtain the same object if I had called the base constructor.
I think the only difference is the other constructors are called. Is my supposition right or there are any other differences?
Classic example of slicing. A varA = C(); leaves you with object of static and dynamic type of A. As a result, C* varC = static_cast<C*>(&varA); exhibits undefined behavior.
You can store a complete derived class in a base-class pointer, however:
int main() {
A* varA = new C();
C* varC = static_cast<C*>(varA);
varC->f();
cout << "varC->a is " << varC->a << endl;
cout << "varC->b is " << varC->b << endl;
cout << "varC->c is " << varC->c << endl;
} // oops, forgot to delete varA/varC, memory leak!
I want to know know how does g++ compiler knows which table to use if their are multiple vtable present in a base class. Like the following example.
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
class sample1
{
private:
int b;
public:
sample1():b(34)
{
cout << "In sample1 constructor" << endl;
}
virtual void print_b()
{
cout << this->b << endl;
}
void print_all()
{
this->print_b();
}
void sample_print_()
{
//cout << this->a << "String : " << this->str1 << endl;
cout << "hello" << endl;
this->print_all();
}
};
class sample2
{
private:
int b1;
public:
sample2():b1(34)
{
cout << "In sample1 constructor" << endl;
}
virtual void print_b1()
{
cout << this->b1 << endl;
}
void print_all1()
{
this->print_b1();
}
};
class sample : public sample1 , public sample2
{
private:
int a;
char *str1;
public:
sample():a(12),sample1()
{
strcpy(this->str1,"hello world");
cout << "In Constructor" << endl;
}
~sample()
{
free(this->str1);
cout << "In Destructor" << endl;
}
void sample_print()
{
//cout << this->a << "String : " << this->str1 << endl;
cout << "hello" << endl;
this->print_all();
}
virtual void print_a()
{
cout << this->a <<endl;
}
};
In above example, child class sample has two parent classes sample1 and sample2 and each of these class have vtable of their own. What if i call a virtual function from sample(child class)? How does the compiler know, in which class that virtual function is present so that it call use that particular vtable pointer ? I know their will be two vtable pointer present in sample(child class) class , so how does compiler know which one to use ?
I have an explicit function that takes a reference to the base type of a class. What is the proper way to pass that in?
I am currently doing a static cast:
#include <iostream>
using namespace std;
struct Base
{
Base() { cout << "Base Constructor" << endl; }
Base(Base const& c) { cout << "Base-Base Constructor" << endl; }
};
struct Derived : public Base
{
Derived() { cout << "Derived Constructor" << endl; }
explicit Derived(Base const& c) { cout << "Derived-Base Constructor" << endl; }
Derived(Derived const& c) { cout << "Derived-Derived Constructor" << endl; }
};
int main()
{
Base B;
cout << "\n";
Derived D;
cout << "\n";
Base* test1 = new Derived(D);
cout << "\n";
Base* test3 = new Derived(static_cast<Base>(D));
cout << "\n";
Base* test2 = new Derived(B);
cout << "\n";
return 0;
}
but that calls the copy constructor of the base class.
I could pass *static_cast<Base*>(&D), but that seems a bit hackish. I feel like I am just overlooking a simple way to do this. Thanks.
Use this:
static_cast<Base&>(D)
Or this:
static_cast<const Base&>(D)
#include <iostream>
#include <cstdlib>
using std::cout;
class A
{
public :
A() { cout << "A()" << this << "\n";}
~A() { cout << "~A()" << this << "\n";}
//void func() { }
virtual void debug(int a) { cout << "A::debug";}
private :
int a;
};
class A1 : public A
{
public :
A1() { cout << "A1()"<< this << "\n";}
~A1() { cout << "~A1()"<< this << "\n";}
private :
int a1;
};
class A2 : public A
{
public :
A2() { cout << "A2()"<< this << "\n";}
~A2() { cout << "~A2()"<< this << "\n";}
private :
int a2;
};
class B : public A1, public A2
{
public :
B() { cout << "B()"<< this << "\n";}
~B() { cout << "~B()"<< this << "\n";}
void debug() { cout << "B::debug()"; }
private :
int a3;
};
int main()
{
cout << "sizeof(int)" << sizeof(int) << "\n";
cout << "sizeof(void*)" << sizeof(void*) << "\n";
cout << "sizeof(A): " << sizeof(A) << "\n";
cout << "sizeof(A1): " << sizeof(A1) << "\n";
cout << "sizeof(A2): " << sizeof(A2) << "\n";
cout << "sizeof(B): " << sizeof(B) << "\n";
B b;
b.debug();
}
output :
sizeof(int)4
sizeof(void*)4
sizeof(A): 8
sizeof(A1): 12
sizeof(A2): 12
**sizeof(B): 28**
A()0x28fef4
A1()0x28fef4
**A()0x28ff00**
A2()0x28ff00
B()0x28fef4
B::debug()~B()0x28fef4
~A2()0x28ff00
~A()0x28ff00
~A1()0x28fef4
~A()0x28fef4
Both A1 and A2 are 4(vtbl) + 4(A'sint) + 4(respective int) = 12 bytes but B is 28 bytes
I know its not guaranteed but what could be the possible use of those 4 bytes...I dont see any padding issues ? Can anyone point out what am I missing ?
sizeof(A): 8
The type A has a member of type int which in your platform is 4 bytes. It also has a virtual function, which means that a vptr (virtual table pointer) is allocated for each object of your class, the size of it is another 4 bytes.
**sizeof(B): 28**
B contains one object of type A1 (12 bytes), and an object of type A2 (another 12 bytes) and it adds another int for a total of 12+12+4 = 28 bytes. This is quite straightforward.
machine word size alignment of data items within structures.
See structure packing for more information.
Multiple inheritance will produce implementation-specific memory layouts of possibly different sizes.
Virtual tables and virtual pointers for multiple virtual inheritance and type casting