C++ :: Does Polymorphism Affects Operators Overloading?
Nov 24, 2013
I must overload [] but at the same time I must use polymorphism. I wonder if using polymorphism affects operators overloading since when I modified the first class by writing "virtual":
virtual void mostrarDatos(char*, char*, char*);
virtual void calcularEdad(int);
So I can do the polymorphism, it affects the part of the code where suppose to do an addition:
s=student1+=student2;
t=student3+=student4;
u=s+=t;
if I do that, it shows some strange numbers instead of the right ones. Here is the complete code:
.h
#ifndef PERSON_H
#define PERSON_H
#include <iostream>
using namespace std;
class persona {
[Code] ......
View 2 Replies
ADVERTISEMENT
Nov 7, 2014
I have two class GameOfLife and Cell and i want to overload square braket for class GameOfLife."if g is a GameOfLife object, g[10][5] will return the Cell at row 10 and column 5. If there is no such Cells, then it will return a new Cell with position (-1000,- 1000)."
but if g[10][1000] and 1000>cols,then it returns different Cell exp (3,2) How i do control the col ( [row][col] )?
Code: vector<Cell> GameOfLife::operator [](const int row){
vector<Cell> rowCell;
for(int i=0; i<cols; ++i)
{
if( isLive(row,i) )
rowCell.push_back( Cell(row,i) );
else
rowCell.push_back( Cell(-1000,-1000) );
}
return rowCell;
}
View 6 Replies
View Related
Oct 30, 2014
I have a small piece of code that used the set::insert function on a set of myClass. For that, I need to overload the < and > operators, which I have, but I still get a huge error saying it can't compare.
set<MyClass> mySet;
MyClass myClass
All the class information gets filled in. Then, I try to insert...
mySet.insert(myClass);
bool operator<(MyClass &lhs, MyClass &rhs) {
return lhs.name < rhs.name; //name is a string
}
The error says
...stl_function.h:230:22: error: no match for 'operator<' in '__x < __y'
MyFile.h:80:6: note: candidate is bool operator<(MyClass&, MyClass&)
View 5 Replies
View Related
Aug 28, 2014
I made a program that allows the user to enter information of credit cards on an array of size 5, however I need to allow the user to compare the five credit cards with each other and I am having problems with this particular part. I made my bool operator functions for the operator< and the operator> but how to make the user be able to select which cards he wants to compare and how to compare them. My code is the following:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int SIZE = 5;
enum OPCIONES {CARGAR=1, ABONAR, NADA};
[Code] ......
View 2 Replies
View Related
Dec 20, 2013
I build a nice class that i need the output be possible in char * and in string. But how I can do for the compiler don't be confused between them?
Code:
operator char*() {
return (char *) result.c_str();
}
These works fine. and for string, i must casting it. but i want do anotherone for string... how can i do it? I tried:
Code:
operator string() {
return result;
}
But the compiler stays confused or something
View 14 Replies
View Related
Apr 16, 2014
S I want to have different >> operators for several derived classes. Has I tested...
Code: class base{
friend std::istream & operator>>(std::istream & in, base & v);
public:
base();
[Code]......
I noticed that the base operator is the only one being called for all 3 objects. which makes sense and now that I think about it I am more surprised that the "derived operators" compiled at all.
Still, how would I go about declaring different overloaded operators for the different classes?
View 4 Replies
View Related
Nov 11, 2014
I am stucked in a problem of overloading arithmetic operators such as "+,*" for a class in the form
class Point {
int N; // dimension of the point
double *Pos; // length of N
}
My assign operator is :
Point& Point::operator= (const Point& pt) {
N= pt.N;
if(Pos == NULL) Pos = new double[N];
memcpy(Pos, pt.Pos, N*sizeof(double));
[Code] ....
The add operator "+" is:
Point operator+( const Point& pt1, const Point& pt2 ) {
Point ptr = Point(pt); // this is a constructor
for (int i=0; i<pt1.N; i++) ptr.Pos[i] += pt2.Pos[i];
return ptr;
}
Based on the above overloading, What I am going to do is :
P = alpha*P1 + beta*P2; // alpha and beta are double constants, P1 and P2 are Points objes
It is ok with Intel C++ 14.0 compiler, but does not work with the microsoft visual c++ 2012 compiler in debug mode in visual studio 2012.
I stepped in those operators and found that visual c++ compiler deconstructs the ptr in operators "*" and "+" before its return while intel c++ finished the operation P = alpha*P1 + beta*P2; and delete those ptrs at last.
Portability of my operator overloading is worse. How to get those arithmetic operators overloading for class with pointers in it.
View 3 Replies
View Related
Sep 25, 2013
the question am having problems with..
1.Write a class function that defines adding, subtracting, multiplying and dividing fractions by overloading standard operators for the operations.
2. Write a function member for reducing factors and overload I/O operators to input and output fractions. how would i set this up?
View 5 Replies
View Related
Feb 5, 2013
I am making a vector class and am having some problems creating the overloaded arithmetic operators and assignment operators.
Here is an example of my "+=" code as it stands the errors are similar/the same for the other operators except "=" operator which works fine:
Vector3& Vector3::operator+=(const Vector3 &rhs) {
Vector3 tmp = *this;
Set(tmp.getX() + rhs.getX(), tmp.getY() + rhs.getY(), tmp.getZ() + rhs.getZ());
return *this;
}
I have tried a lot of different approaches ad always get the error:
error: passing 'const Vector3' as 'this' argument of 'double Vector3::getX()' discards qualifiers
error: passing 'const Vector3' as 'this' argument of 'double Vector3::getY()' discards qualifiers
error: passing 'const Vector3' as 'this' argument of 'double Vector3::getZ()' discards qualifiers
View 5 Replies
View Related
Apr 4, 2013
class Base
{
.....
.....
.....
virtual void display();
[code]....
in the above polymorphism why is it called runtime polymorphism when i can say seeing the code itself that display() function in derived gets executed with ptr->display(),so how does it become runtime polymorphism when i could get decide at compile itself ???
View 6 Replies
View Related
Dec 29, 2012
How can we calculate tax of vehicle with polymorphism? There are 3 types of vehicles: long, commercial, and private vehicles' classes. There is a common class about all vehicles.
BASE class:
1.Brand and series name (such as Toyota Corrolla, Isuzu etc.)
2.Year of production (you can term it model)
3.Engine size in dm3
4.Owner’s name (including surname) and identity
5.Plate number.
COMMERCİAL :
1.Number of seats (apart from the driver)
2.Data to indicate whether the commercial vehicle is allowed to operate at night.
LONG :
1.The tonnage (max load in tons)
2.Data to indicate whether the long vehicle is allowed to carry goods internationally.
PRİVATE:
1.The class label which can be one of {A,B,C} .
View 1 Replies
View Related
Oct 20, 2014
I have been reading up about object oriented programming recently and have come across 'Encapsulation, Polymorphism and Inheritance' as i understand it so far all OOP programs should use these three concepts. So i started thinking how do i get these concepts into my program as i am using WPF C# and i could not really find much good info about how these concepts apply to WPF programs.
Or do these concepts just not work with WPF programs?
View 5 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
Sep 16, 2014
I have couple of objects which are using some amount of methods. Right now my application is not OOP and i am going to transfer it to OOP. So i would create each class for my each object. Almost all methods are in use for each object, the only one thing which is changing some of those objects passing not all parameters inside specific method. I can go two ways one is prepare interface for all methods i got and each of my classes could implement its own definition for it but other way almost all would implement exactly the same methods but with different parameters so maybe its better to create base class then for each object do inheritance from base class (polymorphism). inside base class i can prepare base methods and classes which will inherit from that class would override those methods for requirements they want.
So imagine: You got:
Memory
CPU
Latency
and all of them using mostly all of those same methods (only arguments for one of them could be use different way):
ExecuteQuery()
ExportToExcel()
PopulateDataTable()
PutValueToReport()
Now its better to do like this e.g:
Base class: Stuff
prop: name, id, date ...
methods to ovveride: ExecuteQuery(), ExportToExcel() ...
classes: CPU, Memory, Latency (inheriting from Stuff)
ovveride methods and align its definition for specific class use (remember mostly only passing args are used or not by specific class)
or go with inheritance
Interface SomeMethods
ExecuteQuery()
ExportToExcel()
PopulateDataTable()
PutValueToReport()
and each class would implemet its own definition.
The most important thing is that those every objects mostly using all of those methods and what is diffrence that one object can use all of available parameters inside this method and other one no. What i should do? Go with interface or inheritance and polymporfizm inside base class?
View 2 Replies
View Related
Nov 30, 2013
I defined a virtual class and three other classes based on it. I want to use them like this:
int main() {
Dirichlet_t D;
Neumann_t N;
Cauchy_t C;
PDEBoundary_t * B1=& D;
PDEBoundary_t * B2=& N;
PDEBoundary_t * B3=& C;
[Code] .....
but I got two major errors
1: "object f abstract type is not allowed" error.-----why not?
2: "the derived class must implement the inherited pure virtual method"-----Did't I?
View 15 Replies
View Related
Dec 10, 2014
Having issues with program to create a shape area calculator with circle square and rectangle. the uml goes as follows:
Where the UML has shape as the abstract class with public area():double, getName():string,and getDimensions:string, rectangle derived from shape with protected height, and width, and a public rectangle(h:double, w:double), followed by a derived square from rectangle with just a public square(h:double), and finally a circle derived from shape with a private radius, and a public circle(r:double).
[URL]
Have linked my program and it is giving me the following compiler errors:
error: 'qdebug' was not declared in this scope line 15 of main
error: cannot declare variable 'shp' to be of abstract type 'shape' line 22 of main
error: expected primary-expression before ')' token lines 29 -31 of main
(note previously had qstring as a header file yet changed to string since I was getting error qstring was not declared in this scope.)
View 5 Replies
View Related
Mar 2, 2014
I've been working on this project which inserts data for different types of books lately, and I'm trying to utilize inheritance and polymorphism. The issue I've been having is after I create an object with my MediaFactory, I go to insert data into that type of object, but it won't reach the correct child class. The parent class in this case is MediaData. The class I'm trying to reach is Childrens, and the class that falls in between is called Book. The function I'm calling to insert the information is setData(ifstream&). This function simply places the information from a txt file into an object with the insertion operator.
Right now the program runs into the setData function of Book instead of Childrens. I need Childrens so I can enter all the required attributes (title,author,year). The call to this function is in MediaManager through the function called buildMedia, and my test is running into the case if (type == 'Y'). From there a pointer of type MediaData is created and pointed to a new object returned of type Childrens. I'm using my debugger in Xcode which does show that the correct object type (Childrens) was created.
I've tried a couple things so far. First I created another function called getData. From there I passed in *media and infile (txt input file) into that function, which then passed it right into setData with a pointer to the object and infile in the parameter. That didn't work, so I also tried going back into Childrens and removing MediaData from all my virtual functions and replacing it with Book. I got the same result when that happened; It morphed into Book class instead.
I have a portion of my UML as a reference. Childrens is a Book; Book is a MediaData. I also included all code for MediaManager, MediaHash, MediaFactory, MediaData, Book, and Childrens.
I did not include the operator overloads in the .cpp files to eliminate some redundancy.
//-----------------------------------------------------------------------------
// MediaManager.h
// Manager class for MediaData type objects
//-----------------------------------------------------------------------------
#ifndef MediaManager_H
#define MediaManager_H
#include "MediaHash.h"
#include "MediaFactory.h"
#include "MediaData.h"
using namespace std;
class MediaManager {
[Code] ....
View 3 Replies
View Related
Mar 19, 2013
Below code produces run-time segmentation fault (core dumped) when execution reached line 53: delete [] array
Code 1:
#include <cstdlib>
#include <iostream>
using namespace std;
#define QUANTITY 5
class Parent {
protected:
int ID;
[Code] ....
Output of code 1:
Constructor of A: Instance created with ID=1804289383
Constructor of A: Instance created with ID=846930886
Constructor of A: Instance created with ID=1681692777
Constructor of A: Instance created with ID=1714636915
Constructor of A: Instance created with ID=1957747793
A::showID() -- ID is 1804289383
A::showID() -- ID is 846930886
A::showID() -- ID is 1681692777
A::showID() -- ID is 1714636915
A::showID() -- ID is 1957747793
Try to delete [] array..
Segmentation fault (core dumped)
Question: Why does segmentation fault happen in code 1 above?
View 9 Replies
View Related
Oct 19, 2014
I am making a very basic parent/child class based program that shows polymorphism. It does not compile due to a few syntax errors reading "function call missing argument list. Lines 76 and 77, 81 and 82, and 86 and 87.
#include<iostream>
using namespace std;
class people {
public:
virtual void height(double h) = 0;
virtual void weight(double w) = 0;
[Code] ....
View 4 Replies
View Related
Jun 17, 2014
The + operator has left to right associativity then for the program f1() + f2(), why f1() is not called first compared to f2()?
View 5 Replies
View Related
Dec 20, 2013
I wrote this program using an online compiler i am getting a lot of errors.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string birthmonth;
string birthday;
[Code] ....
View 6 Replies
View Related
Jul 14, 2012
I have a code that uses multi threads using OMP. However, Inside the code I allocate too many memory using "new".
I know that the memory allocation using new must be done in serial. Therefore I am not getting a good performance out of the multi-threaded program.
I thought about allocating a big memory only once, and then advance the pointer every time I need to allocate a small memory.
For example, if I need to allocate chunks of 7 doubles:
Code:
main_memory = new double [10000];
double* x1 = main_memory;
main_memory+= 7;
double* x2 = main_memory;
main_memory+= 7
However, I do not know how to handle the memory deallocation. Beside, this is not thread safe method because main_memory is shared by all threads.
May be there is a boost library that does this, which I am not aware of.
View 3 Replies
View Related
Apr 3, 2013
Came across the foll code:
#include<stdio.h>
main() {
int i=4,j=7;
j=j||(printf("you can")&&(i=5));
printf("%d %d",i,j);
}
output: 4 1
Although I am specifying the braces for the && operator so that it gets executed first..Then also the value of i remains 4 only..Why does not it gets changed to 5??Also the printf does not execute??
View 9 Replies
View Related
May 20, 2013
Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply values that can be expressed as an integer, such as the value of a char).
So does that mean switch statements can only test if variable == value and nothing more, like > < >= <= != etc... ? I tried to make a program to test this and it seems like switch statements are limited to == but I'm not sure, maybe I'm doing something wrong.
This is the program I tried to make to test this:
Code:
#include <stdio.h>
int main () {
int n;
[Code]....
So is it true that switch statements only work with the built in == operator? if that was the case then I would feel rather meh about switch statements.
View 7 Replies
View Related
Jun 14, 2014
I'm experimenting with a custom memory-pool for my application, and I initially planned to override the global new and delete operators to allocate memory in this pool. But since I'm using QT, this will apply to all the QT-related stuff as well. Should I instead just override the new and delete operators per class?
View 2 Replies
View Related
Apr 27, 2014
I have two files NumDays.h and ClientProgram.cpp
clientprogram.cpp basically has the main module below
int main(){
// Initialized UDT object Declarations
NumDays hoursWorked_John; // Instantiate with Default Constructor
NumDays hoursWorked_Sue(36.9); // Instantiate with Initializing Constructor
NumDays hoursUsed_Sue(4.5); // Instantiate with Initializing Constructor
[Code] .....
I can't figure out anything to put in for NumDays.cpp so it's not there.
View 5 Replies
View Related