C++ :: Using Virtual Functions In Base Classes
Oct 19, 2014
I recall when I first started playing with C++ I was told that you should never use virtual functions unless you absolutely cannot think of a better way to do whatever you are attempting. This is something I have tried to stick to over the years - and indeed is probably why I have never used inheritance or polymorphism much in my own programmes.
However, I notice through a great deal of the code examples offered to questions here and even over on StackOverflow that commentators show no hesitation to recommend code that involves virtual functions. More so, I have even seen several instances here where - what I was taught as, but they may well have a different official name - 'pure virtual functions' (those with definitions inside a class of something like virtual int function_name(void)=0) are demonstrated and I was very clearly taught to avoid those like the plague.
I was wondering therefore has the official thinking changed since the middle nineties on when - and even whether - to use virtual functions in your programmes?
View 9 Replies
ADVERTISEMENT
Sep 11, 2014
So I have 2 seperate base classes, (note that I removed the variables and functions that do not relate to the topic) Object.h
class Object{
public:
Object();
~Object();
[Code].....
The error I get is saying I am calling a function declared with one calling convention with a function pointer declared with a different calling convention and this makes perfect sense because for some reason, the function pointer is pointed at the virtual function Object::update but I can't figure out why and how to make it point at the virtual function Drawable::getImage.
Also, the virtual update function is called in a different place just before this and works correctly.
View 6 Replies
View Related
Jan 26, 2013
when I should use pure virtual functions.On the one hand, "TOY" for example should be an abstract class since theres no such thing as "TOY" , there are "toy cars", "toy fighters" etc , but on the other hand I need to force it somehow to be abstract since theres no really a function that any toy should have and implement on his own way (except PRINT maybe).
when I should REALLY use pure virtual functions? And if I want to avoid people from creating TOY objects (for example), the only way is PURE virtual functions. right?
View 4 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
May 4, 2013
How can I access the virtual base class? This is a practice exercise from c++ primer plus 6.
The problem is that the name becomes No Name instead of the name specified when creating the gunslinger, I don't know how I can call the virtual base class explicitly
Output,
#ifndef PERSON_H_
#define PERSON_H_
#include <string>
#include <iostream>
#include <cstdlib>
using std::string;
class person
[code]....
View 7 Replies
View Related
Jul 1, 2013
I've got two classes, which are both derived from the same two base classes. Here's a representation of the actual code:
Code: #include <vector>
class BaseClassA {
};
class BaseClassB {
};
class TestClassX
: public BaseClassA,
public BaseClassB
[code].....
Basically, I'd like to know if it is possible to cast directly from a BaseClassA pointer to a BaseClassB pointer, without casting to the child class first.
View 10 Replies
View Related
Nov 26, 2013
We want a solution in C++ that must be able to do the following:
Given a string of particular type, lets say 'A', we want to find all the types that derives from 'A'.
Instantiate new objects out of the types that are derived from 'A'.
E.g. Lets say we have a class, VehicleEntity. VehicleEntityhas child classes, PassangerCarEntity, TruckEntity, TrainEntity, BoatEntity.
We are unsure what vehicle entities there may be as the a library could be added containing more VehicleEntities. E.g. an AirplaneEntity thaterives from VehicleEntity could be added after deployment.
In the application, when a user wants to select a VehicleEntity, the user should be able to pick any of the entities deriving from VehicleEntity. This includes the PassangerCarEntity, TruckEntity, TrainEntity, BoatEntity and AirplaneEntity. The user selects an Entity, lets say AirplaneEntity, A new object of type AirplaneEntity must be instantiated.
The following is an concept example in C# of what we want to achieve in C++.
In C# the items for the dropdown list can be retrieved as follows:
Type vehicleEntityType = typeof(VehicleEntity);
List<Type> types = new List<Type>();
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
[Code] .....
We are aware that standard C++ does not contain any Metadata on its objects, and thus it is not possible without a workaround. It does not seem possible with RTTI and boost.Mirror.
View 7 Replies
View Related
Apr 30, 2013
how to create a base class that is derived (inherited) by three other classes?
View 12 Replies
View Related
Jan 31, 2014
I was reading about the CRTP, and I can't for the life of me understand it's advantages over virtual functions.
Unless you're coding embedded systems, and can't afford the few extra bytes for the vptr, or coding something requiring high-performance, where every nanosecond counts, I just don't see why the CRTP is so attractive. It just adds more text and forces every user class that wants to use the CRTP'd hierarchy to become a template class.
I tried implementing my Functor hierarchy with the CRTP instead of virtual functions...All it did was clutter my files with angle brackets and made the whole thing look very ugly.
View 14 Replies
View Related
May 2, 2014
if we do a virtual functions(polymorphism) why we need re-declare the functions(when we create a new class derived from other)?
View 10 Replies
View Related
Oct 14, 2013
I try the functions pointers too, but without success. I understand the objects are the way for work with class's. until here fine. But why i can't change the virtual functions from an object? is there anyway for do it? Ican't do, outside of classfunctions, these code:
#include <iostream>
using namespace std;
class test {
public:
virtual void created(){};
[Code] ....
How i can validate these line:
void a::created()
???
View 2 Replies
View Related
Feb 15, 2013
Is it possible to do something like this:
class A //parent {
public:
virtual void DoSomething() = 0;
};
class B : public A //child {
public:
void DoSomething(string s) override;
}
Where the child member function overrides and changes the parents member function.
I need to pass an array of key states to the Controller class' Update() function but don't want to send it to every class derived from Object (like Controller).
Is this possible or do I have to overload the original Update() member function (but I would need to define the method in Object then (i.e remove the pure virtual function (=0)))
View 4 Replies
View Related
Aug 7, 2013
I'm working with inheritance and pure virtual functions, and I want to overload an output stream operator. However, every time I run the program I get this: 0x7fff00ee98c0.
I'll include a base class and a derived class so you can see what I'm talking about.
Base:
#include <iostream>
using namespace std;
#ifndef _Insurance_h_
#define _Insurance_h_
[Code]....
The application is something like this (I'm assuming the user has already inputted the name, salesperson, make, model, etc):
#include "Auto.h"
#include <iostream>
using namespace std;
#include <vector>
vector<Insurance *> sales;
[Code] .....
View 4 Replies
View Related
Apr 13, 2014
I'm writing a program that calculate the carbon footprint for car, building, and bicycle. i have three classes building, car, bicycle. class called carbonfootprint have the pure virtual and should have the formula, but i didn't find it. having a little bit hard understanding some requests. like,
• Write an abstract class CarbonFootprint with only a pure virtual getCarbonFootprint method. Have each of your classes inherit from that abstract class and implement the getCarbonFootprint method to calculate an appropriate carbon footprint for that class.
• The main() function in the given program creates objects of each of the three classes, places pointers to those objects in a vector of CarbonFootprint pointers. You need to iterate through the vector, polymorphically invoking each object’s getCarbonFootprint method.
// Test program for CarbonFootprint and implementing classes.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector< CarbonFootprint* > list;
// add elements to list
[Code] ....
View 4 Replies
View Related
Mar 6, 2015
I have a hpp file with a list of inline finctions like this:
Code:
inline int check() {
return 1;
}
inline int check_1() {
return 1;
}
... What I would like to do is to include them into several unrelated classes. How can I do this. Can I just add the hpp inline functions in headers of my class containing files or not. I mean if they are not defined as class functions how can they be called. I don't understan the logic.
View 2 Replies
View Related
Dec 29, 2013
I have a situation: I have a class character
class Character;
class Village;
class Character {
public:
//Functions
void charGen(); //Character creation
[Code] .....
According to the Friendship and Inheritance tutorial [URL] ...., that code should work, but it doesn't. I am given an error: undefined reference to questsCompleted
The compiler I am using is Code::Blocks ....
View 4 Replies
View Related
Jan 19, 2014
I need to access the functions of the derived classes from a vector of objects of base classes (can't believe I wrote it). Here a Diagram for you to understand:
So as you see, I need the function Use() from the Usable class, to be able to be called from the vector like:
inventory.at(x)->Use()
View 14 Replies
View Related
Jul 5, 2013
I'm developing a stack using a linked list. I have to develop two friend functions to do something with the list. But I've tried to understand the friendship, without any consistent result.
Extract of code:
Code:
class Element {
public:
int Data;
Element *nextElement;
Element(int Element) {Data = Element; nextElement = NULL;}
~Element() { }
[Code] ....
I have no errors, but I cannot access the private properties of the class.
The thing I would like to do is: sum the elements of the stack with a friend function.
View 7 Replies
View Related
Oct 11, 2014
I'm trying to print a single linked list backward with functions/classes. I have created the main file and 3 header files. But I'm getting an error on one of the header files, linkedListIterator after adding #include "linkedListType.h". It says that "linkedLlistType.h" is calling itself. And when I try to run it, I get an error of "too many header files." I have tried changing the headers many times, but nothing seems to work.
.cpp file:
/*(Printing a single linked list backward) Include the functions reversePrint and recursiveReversePrint, as discussed in this chapter, in the class linkedListType. Also, write a program function to print a (single) linked list backward. (Use either the class unorderedLinkedList or the class orderedLinkedList to test your function.)*/
#include "linkedListType.h"
#include "orderedLinkedList.h"
#include "linkedListIterator.h"
#include <iostream>
using namespace std;
struct nodeType
[Code] ....
header files:
[URL] .... (error in this header file)
[URL] ....
View 9 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
Feb 27, 2015
I just wanted to add strings in any base form (example 1101+100 = 10001 in base-2 but it could be added using any base-form like in base-3 to base-36) and I'm having a big trouble with my code because it gave me incorrect results.
addition(char st[], char st2[], int base){
int i, j, carry = 0, ans, len, o=0, z=1, l=0;
char final[50];
if(strlen(st)>=strlen(st2))
len = strlen(st);
else
len = strlen(st2);
[Code] ....
View 1 Replies
View Related
Apr 15, 2013
How would you convert say "238273615237287352536266362524382737272" base 10 to a base x number contained within a string of characters?
View 2 Replies
View Related
Mar 25, 2013
I got this algorithm of conversion and now I'm stuck at how to code it.
"Algorithm to Convert From any Base to Base 10 Decimal."
Let 'n' be the number of digits in the number. For example, 104 has 3 digits, so 'n'=3.
Let 'b' be the base of the number. For example, 104 is decimal so 'b' = 10.
Let 's' be a running total, initially 0.
For each digit in the number, working left to right do:
Subtract 1 from 'n'.
Multiply the digit times b^n and add it to 's'.
When done with all the digits in the number, the decimal value should be 's' .
View 6 Replies
View Related
Mar 20, 2014
I need to convert an integer, for example 10, to its base 16 equivalent, 16. I found this code that converts a base 16 number to base 10, but I need the opposite. Plus, this code doesn't seem to work properly with input values under 32.
Code:
uint32_t input = 16;
uint8_t temp;
temp = ((input>>8)*100)|((input>>4)*10)|(input&0x0f);
View 13 Replies
View Related
Dec 27, 2012
class Parent{
public:
virtual int width();
virtual int height();
int area(){return width()*height();};
[Code] ....
View 10 Replies
View Related
Oct 5, 2013
I have an array of (Student)classes created in Manager.h, which contains a new instance of class Name (name),(in Student.h)How would I go about accessing the SetFirstName method in Name.cpp if I was in a class Manager.cpp? I have tried using Students[i].name.SetFirstName("name");
// In Manager.h
#include"Student.h"
class Manager
{
[Code]....
View 2 Replies
View Related