I have an assignment in which I need to translate some Ada code to C++ code, making it as similar as possible to the Ada code. The Ada code is as follows
type Shape is (Circle, Triangle, Rectangle);
type Colors is (Red, Green, Blue);
type Figure(Form: Shape := Circle) is
record
Filled: Boolean;
Color: Colors;
case Form is
when Circle =>
Diameter: Float;
when Triangle =>
Left_Side: Integer;
Right_Side: Integer;
Angle: Float;
when Rectangle =>
Side_1: Integer;
Side_2: Integer;
end case;
end record;
I know I could use a class but judging by the language of the question and the personality of the teacher I assume he is looking for a struct. I am just unclear as to how to create the logic required for the different cases inside of a struct. The teacher is very particular so I assume that the smallest memory footprint is required.
I am a CSc student so forgive me if the solution is simple.
Thanks!
Update:
So the final answer was simpler than I thought.
enum Shape {Circle, Triangle, Rectangle};
enum Colors {Red, Green, Blue};
struct Figure {
bool Filled;
Colors Color;
Shape Form;
union {
float Diameter;
struct {
int Left_Side;
int Right_Side;
float Angle;
} tri;
struct {
int Side_1;
int Side_2;
} rect;
};
};
As usual I overthought it. Thanks for all your input!
It looks like you are suppose to derive classes Circle, Triangle, and Rectangle from a base Shape class. There are common properties (Filled, Color) that needs to go into your base Shape, and derived classes will have diameter, or left-right sides, or other additional properties.
An alternative would be to have a type-id field (enum {Circle, Rectangle, ..})in a Shape struct and a union field holding different sub-structures for diameter and other type dependent members. This would look more like the example (and C) but less like C++.
For non-class based answer:
Make the enumerations for the Shape and Color types.
Make structs for the Circle, Triangle, and Rectangle data.
Make a Figure struct containing the filled field, colored field, and a field which is a union of the structs made in #2.
[optional] Make "constructors" for the various shapes that return the struct from #3, properly initialized.
Related
I am currently in an apprenticeship and one of the trainers said "Shaders are object-oriented" as an example for object-orientated programming. To me it means HLSL & GLSL are object-oriented languages.
I never thought of shaders as object-oriented.
But now when I look at this: https://www.khronos.org/opengl/wiki/Data_Type_(GLSL)
vec4 someVec;
someVec.x + someVec.y;
I also see object-orientation, because of the dot. Now I am confused.
I started doing OpenGL and GLSL 2 years ago, it never came to my mind that GLSL is object-oriented.
So I kind of missed out a major point.
I know that these shader-languages HLSL/GLSL derive from their assembly-predecessors.
Can somebody please state if GLSL is indeed object-oriented.
No, OpenGL Shading Language is not object orientated. There are no methods (or even inheritance and polymorphism) in glsl.
The data types behave more like a struct in C, than a class in C++. But of course there a additional options to Constructors and initialize the glsl data types respectively some special Vector and Matrix Operations and components can be accessed by Swizzling.
But that makes the language not to an Object-oriented language, because the concept of objects requires fields of data and procedures (methods) contained in an object. In glsl the general concept of methods is missing.
I also see object-orientation, because of the dot.
That's not what "object orientation" means. The dot is merely the "member access operator", and for all intents and purposes is a combination of some sort of "typecast", "pointer dereferencing" and "pointer arithmetic". All in quotes, because there are not actual pointers involved as far as language and compiler are concerned, but on the silicon level it really boils down to address offsets.
Object orientation means that you can derive classes from other classes, overload and overwrite methods, and so on. Like this (pseudocode)
class A begin
var foo
var bar
method spam()
endclass
class B inherits A begin
var eggs
var bacon
var mixture
method spam() begin
eggs -= bacon
A::spam()
end
method mix(seasoning) begin
mixture = eggs * bacon + seasoning
spam()
end
endclass
GLSL is not an object-oriented language, but it is possible to mimic object-oriented classes using structs with overloaded methods:
struct Rectangle { //define a "base class"
float width;
float height;
};
void new(inout Rectangle self,float width,float height){ //a "constructor"
self.width = width;
self.height = height;
}
float area(Rectangle r){ //an "instance method"
return r.width * r.height;
}
float perimeter(Rectangle r){ //an "instance method"
return (r.width + r.height)*2.;
}
struct Square{
Rectangle super; //Square is a "subclass" of Rectangle
float width;
float height;
};
void new(inout Square self,float width){ //constructor for Square
self.width = width;
self.height = width;
}
void super(inout Square self){ // copy instance variables to superclass
self.super.width = self.width;
self.super.height = self.height;
}
float area(Square self){ //"inherit" this method from the superclass
super(self);
return area(self.super);
}
float perimeter(Square self){ //"inherit" this method from the superclass
super(self);
return perimeter(self.super);
}
void example(){
Rectangle r;
new(r,3.,4.); //initialize an instance of Rectangle
float rectangle_area = area(r); //call an instance method
float rectangle_perimeter = perimeter(r);
Square s;
new(s,3.); //initialize an instance of Square
float square_area = area(s); //call an instance method
float square_perimeter = perimeter(s);
}
Consider the following Enum Class in Java:
package com.gousslegend.deepov;
public enum Color
{
WHITE, BLACK;
private Color opposite;
static
{
WHITE.opposite = BLACK;
BLACK.opposite = WHITE;
}
public Color getOppositeColor()
{
return opposite;
}
}
How can I achieve the same thing with C++11?
Is is possible to have enum methods with C++11?
Should I put my enum in a separate class/file with C++?
Thanks
How can I achieve the same thing with C++11?
In C++ you would be better off defining an enum, along with a free-standing function:
enum Color {BLACK, WHITE};
Color getOppositeColor(Color c) {
static Color opposite[] = {WHITE, BLACK};
return opposite[c];
}
If you are set on modeling Java exactly, make a class with two static members BLACK and WHITE, and use it instead of enum. The use would be limited, though: for instance, you wouldn't be able to use your enum values in switch cases.
Is is possible to have enum methods with C++11?
No
Should I put my enum in a separate class/file with C++?
You should put enum definition and a function prototype in a header; implementation of the function goes in a separate C++ file.
C++'s enums are simple enumerated values, they're not full-fledged classes (enum classes in C++ only provide some additional type-safety).
I would take the following approach to implement the equivalent to how Java's enums are used here:
// Header file
class Color {
Color *opposite_p;
public:
Color(Color *opposite_pArg) : opposite_p(opposite_pArg) {}
Color &opposite() { return *opposite_p; }
static Color WHITE, BLACK;
};
// .C file
Color Color::WHITE(&BLACK);
Color Color::BLACK(&WHITE);
Then, Color::WHITE.opposite() returns Color::BLACK, and COLOR::BLACK.oppsoite() returns Color::WHITE.
I have a class Color that holds values for the red, green, blue, and alpha channels of a color. The class constructor lets you create a new color by specifying values for the four channels. However, for convenience, I would also like to have some "premade" colors available for the programmer. For example instead of having something like
DrawBox(new Color(255, 0, 0));
you would be able to say
DrawRectangle(Color::Red);
Where Color.Red is an instance of Color that lives inside the Color class. How can I declare these instances of Color inside the Color class? I'm sure there's a name for this technique, but I had no idea what search terms to use when I was looking for help online.
I'm not using any built-in or publicly-available classes or libraries because this is part of a personal exercise in creating a basic graphics stack.
Thanks for your help!
First of all, avoid using new. You could use Color as simple value-type.
Now as an answer to your question, yes, you can do that as:
//color.h
typedef unsigned char byte;
class Color
{
public:
//declaration
const static Color Red;
const static Color Green;
const static Color Blue;
public:
Color(byte red, byte green, byte blue);
};
//define the static members in color.cpp file
#include "color.h"
const Color Color::Red(255,0,0);
const Color Color::Green(0,255,0);
const Color Color::Blue(0,0,255);
Then use Color::Red as you want to use.
Newbie...
I want to create a dynamicly growing list that will hold Point variables, a couple of int variables and whatever the colour variable is for Argb.
I'm doing it in Visual Studio C++ 2010
What is the best approach to handle this data within the program? It needs to store location, size and colour of objects that the user makes on the screen so I can draw them back to the Form when I refresh the Form. Currently I have a really nice program that draws squares,circles and lines in different colours and I can move that object around but this is only because I'm still holding onto the current object/shape data.
Create a struct or class to hold the information for one shape, and then use an std::vector to hold a list of them.
std::vector<Shape> myShapes;
If all of your shapes can be described by essentially the same data set, with some variance in size of some pieces of data, e.g the number of "Point varaibles" changes from shape to shape, then have a std::vector inside the shape class to hold them that variable data, e.g:
struct coordinate2D
{
int x;
int y;
};
class Shape
{
coordinate2D position; //the location on the shape
std::vector<coordinate2D> points; // the coordinates of the vertices that make up this shape.
};
//elsewhere
std::vector<Shape> myShapes;
I have class like following:
class Car
{
public:
Car();
// Some functions and members and <b>enums</b>
enum Color
{
Red,
Blue,
Black
};
Color getColor();
void setColor(Color);
private:
Color myColor;
}
I want to:
access to Color values as Color::Red. It is really hardly to understand code when Car::Red is used, when class have a lot enums, subclasses etc.
use type Color as function argument or return value
use variable type Color in switch
I know 3 partial solutions:
Using embedded class Color and enum in it
Using embedded namespace Color and enum in it
Using enum class
1 and 2 solutions solves a Color::Red accession problem, but I can't use functions like Color getColor() and void setColor(Color).
3 solution has a problem: VS2010 doen't support enum class. GCC v.4.1.2 doesn't support it too. I don't know about later versions of gcc.
Yes, I'm working on cross-platform project.
I have found this solution, but it seems ... heavy.
I hope somebody can help me here :)
In current C++ (i.e. C++11 and beyond), you can already access enum values like that:
enum Color { Red };
Color c = Color::Red;
Color d = Red;
You can go further and enforce the use of this notation:
enum class Color { Red };
Color c = Color::Red;
// Color d = Red; <-- error now
And on a sidenote, you now define the underlying type, which was previously only possible with hacky code (FORCEDWORD or so anyone?):
enum class Color : char { Red };
Name the enum inside the nested class (as example one):
class Car
{
public:
struct Color
{
enum Type
{
Red,
Blue,
Black
};
};
Color::Type getColor();
void setColor(Color::Type);
};
When I want to do something like this I tend to use a namespace and a typedef outside of th namespace (though usually I'm doing this globally rather than inside a class). Something like this:
namespace colors
{
enum Color
{
Red,
Blue
...
}
}
typedef colors::Color Color;
This way you use the namespace to get at the actual colors, but the Color type itself is still globally accessible:
Color myFav = colors::Red;