C++ :: A Pointer To Base Class
May 18, 2013
A pointer to base class, if assigned to a derived class, only points to the base part right? So you can only use the base part of the derived class with that pointer and no methods from the derived class?
View 8 Replies
ADVERTISEMENT
Feb 6, 2015
I create an instance of a base class (not derived class) and assign it to base class pointer. Then, I convert it to a pointer to a derived class and call methods on it.
why does it work, if there is a virtual table?
when will it fail?
// TestCastWin.cpp : Defines the entry point for the console application.//
#include "stdafx.h"
#include <iostream>
class B
{
public:
B(double x, double y) : x_(x), y_(y) {}
double x() const { return x_; }
[Code] ....
View 14 Replies
View Related
Mar 21, 2015
In this book, item 3 is about never treat arrays polymorphically. In the latter part of this item, the author talks about the result of deleting an array of derived class objects through a base class pointer is undefined. What does it mean? I have an example here,
Code:
class B
{
public:
B():_y(1){}
virtual ~B() {
cout<<"~B()"<<endl;
[Code] ....
This sample code does exactly what I want. So does the author mean the way I did is undefined?
View 1 Replies
View Related
Aug 29, 2014
I have a query regarding virtual destructor functionality. So below is sample code:
Code:
#include<iostream>
#include<stdlib.h>
using namespace std;
class Base
Code: Base *b = d;
Here b and d now pointing to same memory location.
Now below statement:
Code: delete (b);
Here since my destructor is virtual it will call derived class and base class destructor.
Now my question is, if I use this:
Code: delete (d); // And without virtual keyword in ~Base() {} This call both derived and base class destructor.
So which one is correct form to call and why? Is delete(b) is standard in virtual function mechanism.
Output is:
D1 :: function1()
Base :: function2()
INSIDE D1 DES
INSIDE BASE DES
View 2 Replies
View Related
Jun 28, 2012
I'm trying to implement a class hierarchy and a wrapper class with a pointer to the base class. The base class has operator< overloaded and the implementation makes use of virtual functions as some of the logic for sorting is in the derived classes. Unfortunately, when trying to use the base class operator< from the wrapper, I get a "pure virtual method called".
Below code is meant to illustrate my problem. Unfortunately it crashes on me (upon destruction of vec) and I cannot quite see, why. So two questions:
1. spot the error I made in the code below (having lived in Java-land for the last 5 years, I'm sure I just did some stupid error)?
2. How can I implement Wrapper::operator< to use Base::operator<? I know I could write a function and pass it to sort but I'm interessted if there is a way to actually use Base::operator<.
Code:
#include <vector>
#include <algorithm>
#include <cmath>
[Code].....
View 3 Replies
View Related
Jan 14, 2015
Is there a way to copy a derived class object thru a pointer to base?
For example:
class Base { public: Base( int x ) : x( x ) {}
private: int x; };
class Derived1 : public Base { public: Derived( int z, float f ) : Base( z ), f( f ) {}
private: float f;};
class Derived2 : public Base { public: Derived( int z, string f ) : Base( z ), f( f ) {}
[Code] ....
The question is whether *B[0] would be a Derived1 object and *B[1] a Derived2 object?If not, how could I copy a derived class thru a pointer to the base class?
View 1 Replies
View Related
Aug 12, 2013
I know what are pointer's and how to use them but there is one point i am not able to understand. Below is the example code
I understand everything in the below code except 1 thing why i am using pointer to base class object in vector int the main() Function?
Code:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
// base class
[Code] ...
Here is the lines of code i want to understand.
Code:
vector<Employee*> employees;
employees.push_back(&emp1);
employees.push_back(&mgr1);
I know if i will not use the pointer base class function "virtual double grossPay" will be called for both base class object and derived class object and when i will use pointer with reference to the object because base class function is virtual it will look for same function in derived class and if available it will execute it.
View 3 Replies
View Related
Mar 30, 2013
Say I have 3 classes:
class Player {
public:
virtual func1();
[code]....
Say in my main class, I have a function fight(Player p1, Player p2) and I would like to do something like this in the fight function, given that p1 is the human and p2 is the computer:
//function fight()
fight(Player p1, Player p2) {
p1.func2();
}
//using function fight()
fight(human, computer);
When I compile the program, I got this: error: ‘class Player’ has no member named 'func2()' What can I do to allow p1 to call func2 inside fight()? I'm not allowed to use pointers as the parameter for fight() and have to use the signature fight(Player p1, Player p2).
View 6 Replies
View Related
Jan 21, 2014
The compiler creates virtual table for the base class and also for the derived class whether we override it or not.
That means each class has separate virtual table. when we get the size of the each class with out any data members... the size of base is -- 4 bytes(64 bit) and the size of derived is -- 1
The size of base class 4 is correct since it creates the virtual pointer internally and its size is member data + virtual pointer, but it in this case I have included any data members so it has given 4 byts.
But why in case of derived is 1 byte, since it the derived class has overridden the virtual function from base, this will also contains the virtual pointer which will be pointing to derived class Vtable, it the size of the class suppose to be 4 instead of 1 byte.
#include<iostream>
class A{
public:
[Code].....
View 1 Replies
View Related
Apr 26, 2014
I have my main.cpp like this:
#include <iostream>
#include "curve1.h"
#include "curve2.h"
using namespace std;
int main() {
Curve1 curve1Obj;
Curve2 curve2Obj;
[Code]...
Base class Score has two derived classes Curve1 and Curve2. There are two curve() functions, one is in Curve1 and other in Curve2 classes. getSize() returns the value of iSize.
My base class header score.h looks like this:
#ifndef SCORE_H
#define SCORE_H
class Score {
private:
int *ipScore;
float fAverage;
int iSize;
[Code]...
You can see that I have used curve1Obj to enter scores, calculate average and output. So if I call getSize() function with cuve1Obj, it gives the right size that I took from user in enterScores() function. Also the result is same if I call getSize() in score.cpp definition file in any of the functions (obviously).
.....
The problem is when I call curve() function of Curve2 class in main (line 23) with the object curve2Obj, it creates a new set of ipScore, fAverage and iSize (i think?) with garbage values. So when I call getSize() in curve() definition in curve2.cpp, it outputs the garbage. .....
How can I cause it to return the old values that are set in curve1.cpp?
Here is my curve2.cpp
#include <iostream>
#include "curve2.h"
using namespace std;
void Curve2::curve() {
cout << "getSize() returns: " << getSize() << endl; // out comes the garbage
}
Can I use a function to simply put values from old to new variables? If yes then how?
View 3 Replies
View Related
Jan 16, 2013
Please consider the following code :
#include <iostream>
using namespace std;
class superclass;
class subclass1;
class subclass2;
[Code] ....
As you can see I want to create a dynamically allocated storage of references to a parent class each of which can then point to a child class, how ever I do not know how to extract the child class out again from that array so i may access its variable b.
View 2 Replies
View Related
Jan 6, 2015
Let's say I have a Car object , and it contains inner Engine object.
Code:
struct Car{
Engine mEngine;
};
In order to initialize the engine object NOT by the default constructor (if it has any) , we use initialization semantics:
Code:
Car::Car:
mEngin(arg1,arg2,...)
{
other stuff here
}
Now it gets tricky: Let's say a Car objects has 10 inner objects, each object has about 5 variables in it . Car is a base class for , e.g. , Toyota class. you don't want the Car class to have a constructor with 50 arguments. Can the inner objects of Car be initialized from the base class , e.g. Toyota?
Code:
class Toyota:
Car(...),
mEngine(...),
mGear(..)
{
...
};
The other options are:
1) like said , create a Car constructor which gets 50 arguments, then initialize Car as whole from Toyota - the code becomes less readable and less intuitive
2) Car constructor which get built-objects as arguments and initialize the inner objects with copy constructor . the code gets more readable but then you create many excess objects .
View 5 Replies
View Related
Feb 4, 2014
So I have a base class, lets call it base. In base I have a virtual function called update(), update just couts "base" then I have a class derived from base called derived;
it has a function called update(), update just couts "derived" then I create a vector called Vec it's initialised like this:
std::vector<base> Vec;
then I add an element into it like this
Derived DerElement;
Vec.push_back(DerElement);
then when I type:
for (int i=0; i<Vec.size(); i++) {
Vec.at(i).Update();
}
It outputs:
Derived DerElement2;
DerElement2.Update();
and it outputs this:
#include <iostream>
#include <vector>
class Base {
public:
virtual void Update() {
[Code] .....
and this is it's output:
Base
Derived
Press any key to continue . . .
View 1 Replies
View Related
Jul 15, 2014
I would like to know if there's a way to make a method from a derived class a friend of its base class. Something like:
class Derived;
class Base {
int i, j;
friend void Derived::f();
protected:
Base();
[Code] ......
View 3 Replies
View Related
Oct 12, 2013
I have an example where I have a variable belonging to a base class, but I would like to tell the compiler that it actually belongs to a derived class. How can I do this?
// base class: R0
// derived class: R1
// see function SetR1 for the problem
class R0 {
public:
int a;
[Code] .....
View 5 Replies
View Related
Aug 28, 2013
I just wondering if a base class can call the overridden function from a Derived class?
Here's an example:
//Base Class H
class BaseClass {
public:
BaseClass();
virtual ~BaseClass();
virtual void functionA();
[Code] ....
So basically, when I am creating a new object of Derived class, it will initialize BaseClass and the BaseClass will call functionA but I want it to call the function overridden by Derived class.
I know that if I call newObj->functionA it will call the overridden function. Right now I want the base class to call the overridden function "this->functionA(); in BaseClass" during its initialization. Is it possible to do that?
View 9 Replies
View Related
Dec 24, 2013
Basically, I have a base class called MainShop and it has 3 derived classes which are SwordShop, SpellBookShop and BowShop. I want the base class to be able to call a function from one of the derived classes but no matter what i do, it doesn't seem to work!
Here is my code:
#include "MainShop.h"
//BaseClass cpp
void MainShop::EnterShop(Hero& hero)
[Code]....
I have two other derived classes, but its basically the same concept. I have a function in one of the derived classes and i would like to call it from the base class. This is one my derived classes:
//SwordShop derived cpp
#include "SwordShop.h"
void SwordShop::soldierShop(Hero& hero)
{
/* some code here*/
}
View 4 Replies
View Related
Apr 8, 2014
Base class has an array, whose size is controlled by the derived class.
I can't use the STL and use a 2003 compiler, so things like std::vector and std::array are out. I also can't use dynamic memory allocation.
So I thought of a few options:
1.
template <int N> class myBaseClass { ... int array[N]; ... }
then class MyClass: public myBaseClass<8> ... etc ...
2.
have a int **array in the base and assign in the derived class.
3.
give the base some virtual methods such as int *getArray or even int &getInt for more safety.
View 6 Replies
View Related
May 15, 2013
I understand it is done like this
// Calling the base class constructor
explicit CCandyBox(double lv, double wv, double hv, const char* str="Candy"): CBox(lv, wv, hv)
{
...
}
But how does the compiler know that you are initializing the base "part" of the object?
Or is this the entire reason initialization lists exist, to separate this confusion?
View 4 Replies
View Related
Mar 30, 2013
I'm having some difficulties in understanding the topic which I stated above.
View 5 Replies
View Related
Jan 17, 2012
If Yes, then why this syntax does not works :
class Derived : public Base {
public:
Derived& operator=(const Derived &rhs) {
operator =(static_cast<const Base&>(rhs));
[Code] ....
View 2 Replies
View Related
May 28, 2013
I have an abstract base class - let's call it MyInterface - and a class that most classes in my program inherit from, let's call it MyBaseclass.
Let's assume that all my objects inherit MyBaseclass, some of which also inherit MyInterface. Now I want to collect objects in a container class, MyContainerclass. The container class is only interested in objects that implement MyInterface.
Now I know that all objects that inherit MyInterface also inherit MyBaseclass, but the compiler doesn't know that. MyContainerclass wants to call methods in MyBaseclass, but it collects pointers to MyInterface classes. I can't make MyInterface inherit MyBaseclass, because I will be using classes that I don't want to change (they are part of a framework) that already inherit MyContainerclass. IOW, I can't use virtual inheritance to get a nice inheritance diamond.
To sum up, I want to create a container class that:
1. Collects objects that implement MyInterface.
2. Calls MyBaseclass methods on the collected objects.
View 11 Replies
View Related
Oct 1, 2013
I would like to access (use) a (virtual) method declared in a base class via a pointer to an object belonging to a derived class, which overrides the base method. Is it possible? Up to now I have not been successful. I am including a program with a more detailed description.
// declare a base class T0 with virtual function P, and a derived
// class T1 which overrides P; declare two ptrs, to T0 and T1,
// and generate corresponding objects; calling P via the two
// ptrs gives expected result; however I would like to take
// ptr to T1 object & execute the base function (declared
// in T0); is it possible? I tried all possible casts but nothing
// works; no matter how I cast the pt1 ptr, I always end up executing
// the overriding function (declared in T1)
// actual output (debian 7, gcc 4.7.2-5):
[code]....
View 5 Replies
View Related
Aug 8, 2014
I have something like this
class A{//interface}; //implementation
class B{//interface includes a member of type 'A'}; //in implementation of Class 'B' constructor I write
B::B():A(5){} //class 'A' had a constructor of prototype A(int);
now what compiler tells me is
[Error] type 'A' is not a direct base of 'B'
View 2 Replies
View Related
Oct 14, 2014
I have run into a problem which is mostly just an annoyance. I need to know if i can have pass a derived class to a function which has the base class as its parameter. For example i have been creating a program but i have a function which needs to work for multiple classes all derived from the BaseObject class
Code :
class folder : public BaseObject
{}
class BaseObject
{void function(BaseObject B)}
how would i get the following to work:
function(folder)
View 3 Replies
View Related
Mar 1, 2012
I am working on a program for school and I have managed to get everything to work, except the last portion of the program. It seems that the program is not calling the last function EmployeeSummary. The program will compile, and will accept data and compute overtime pay, etc. Just won't go on to the last function.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class CPayroll {
[Code] ...
View 3 Replies
View Related