C++ :: Implicit Default Ctor - What Is It For
Apr 16, 2013Implicit default ctor does not initialize the built-in data members, so what is it needed for?
View 5 RepliesImplicit default ctor does not initialize the built-in data members, so what is it needed for?
View 5 RepliesIn C++ if no user defined constructor is provided for a class the compiler automatically provides a implicit default constructor.
An implicit default constructor is equivalent to a default constructor with no parameters and no body ?
So what is the use of a implicit default constructor provided by the compiler, if it is not going to do anything ?
1. I designed two classes: Processor and Data.
2. Data represents some data object the user can pass to Processor's public methods.
3. Internally, Processor needs to use InternalData type which is based on the content of Data (I can use Data's public interface to get the required information from it, or construct a Data object using its public constructor when needed, and that's how I have done it so far).
4. To avoid repeating code and localize changes required when Data's interface would change someday, I made conversion functions from Data to InternalData and back inside Processor, as private methods.
Now here comes the kicker:
5. But I'd like these conversions to be implicit inside Processor's methods instead of explicit. And only there.
6. These conversion functions are only for Processor implementation's use. They shouldn't be visible nor accessible from the outside world.
Where the problem lays:
7. InternalData is a library type. I don't have control over it and I cannot modify its interface.
That is, I cannot just add converting constructors or conversion operator member functions to them.You can consider it to be built-in type if you wish.
8. I don't want to put those converters inside Data class either, since it's not its business and it shouldn't know that Processor converts it to something else internally.
Long story short, I'd like to teach the Processor's implementation how to make type conversions between Data and InternalData implicitly, but no one else except Processor should be affected by it. Outside world shouldn't be able to do these conversions or even know about them being done inside Processor's implementation.Is there any way to do it in C++?
The core of the problem seems to be the fact that in C++ defining implicit conversions is possible only from/to a user-defined type when defining this type. I don't know of any way to define such conversions for some other type's internal use only. (Especially when I don't have control about one of these converted types.)
I realize that implicit int rule was removed in C99 but gcc still takes this approach by default. I wonder why this happens:
bbb = 5; // legal
int main(void) {
aaa = 10; // illegal
auto aaa = 10 // legal
Inside function a specifier is needed. Error message with no specifier used is:
error: ‘aaa’ undeclared (first use in this function)
Is this because of linkage - bbb variable has an external linkage so compiler knows that we are defining a variable here while inside mean() we need to show compiler that aaa is defined right here, it does not come from external functions?
Ok, so I'm writing this code and when I build it keeps saying cannot implicitely convert type int to string even though I declared my variables as string. Why is it giving me this error?
private static string Repair()
{
string result="";
string beep;
string spin;
Console.WriteLine("Does your computer beep on startup?:(y,n)");
[Code]...
Following is the code snippet
Code:
[COLOR=white !important]?
1
2
3
4
5 char str1[]="Bombay";
char str2[]="Pune";
char *s1=str,*s2=str2;
while(*s1++=*s2=str2);
printf("%s",str1);
Output of this code comes out to be Pune
But according to me output should be puneay.
Pune should be copied in place of Bomb.and rest should be as it is.
[/COLOR]
I have a problem. I want to set pointers to a default value for both 32 bit and 64 bit compiles. The 32-bit version works as:
enum constants { UNDEFINED = 0xDeadBeef }
if ((unsigned long)ptr == UNDEFINED)
but I can't seem to extend this to 64-bits. I've tried
#if __SIZEOF_POINTER__ == 4
enum constants { UNDEFDATA = 0xDeadBeef };
}; // enum constants
#elif __SIZEOF_POINTER__ == 8
enum constants { UNDEFDATA = 0xDeadBeefDeadBeef };
#endif
with:
if (ptr == UNDEFINED)
but get a message saying the '==' is undefined (I understand this)
Is there any way to setup so that I can change the size of my constants so that the comparisons will always work correctly? I've tried a 'typedef' but the compiler complains at
'typedef unsigned long long ADDR' // won't accept, and
static const SlipCellBase * const TEMPORARY = (SlipCellBase&)0xFFFFFFFFFFFFFFFF; // illegal conversion
enum doesn't work (because it's an int?)
First I wrote a Binary-tree class to draw a binary tree on the window. The nodes were small circles. Then I become wanted to change the shape of the nodes from circles to triangles by another class, Binary-tree-derived which is derived from Binary-tree class. I wrote the below code to do the job but I get two errors about constructors. First, code:
/* The binary-tree class, one of the topics that has been said in Programming Principles and Practice using C++ book by Biarne Stroustrup.
This code is written by R Abbasi (s.rabbasi@yahoo.com) */
#include <Simple_window.h>
[Code].....
Errors are:
Error12error C2512: 'Binary_tree' : no appropriate default constructor availablec:userscsdocumentsvisual studio 2012projects est_1 est_1 est_1.cpp91
13IntelliSense: no default constructor exists for class "Binary_tree"c:UsersCSDocumentsVisual Studio 2012Projects est_1 est_1 est_1.cpp91
How to create default arguments in C? Is there any way to make default arguments ( i mean any alternative for them).
View 5 Replies View RelatedHow do you write a default constructor?I need to use a default constructor that will initialize the data members:
- salesPerson to “Unknown”
- noOfWeek to 13
- amount to point to an array of thirteen 0.00s.
This is my weeklysales class
class WeeklySales {
char* salesPerson;
double* amount; // Pointer to an array
int noOfWeek; // Size of the array
};
Here's my attempted code:
//default constructor
WeeklySales (){
salesPerson="Unknown";
noOfWeek = 13;
amount = 0.00;
}
A compiler auto created default constructor is called a synthesized default constructor. It will initialize the built-in members to 0 or not depends on where the class object is defined? if I define a class
class point{
public:
double x, y;
};
if I define point point1; in global scope then point1.x and point1.y will be initialized to 0, if I define point point2; in a local scope, then its x and y won't be initialized? If it is like this, then I believe if there are built-in type members in a class, then the synthesized default constructor is almost useless!
I have an inherited class that essentially manages a Qt Window.
It is as follows (prototype below):
class QTMyOpenGLWindow : public QWindow, protected QOpenGLFunctions {
Q_OBJECT
[Code] ....
Now, I can understand the confusion of the compiler, but the functionality as I laid it out works for me (I can create the class with just specifying the parent and also have the option of preventing auto-initialization when creating). But, is there a better approach?
I am trying to figure out what's the best way to accomplish something like this:
void function(t1 a=0,t2 b=0){/*...*/};
t2 value;
function(value);
That would throw a compile error, since the first argument that is being passed to the function (value) is considered the first argument in the declaration (a), which is of type t1. So, is there a way to force my function to consider value as the second argument instead of the first one? I am aware that this could be done using overloading, but the larger the amount of arguments, the larger amount of possibilities, so it might end up with a huge list of overloads. The best case scenario would be being able to set things like:
void function(t1 a=16,t1 b=0,t2 c=1){/*body*/};
function(b=3,a=0);
but I'm not aware of such feature in C++.
Would it be possible to design some sort of macro system to take care of this?
So a long time ago I messed around with DirectX but I don't remember where it gets placed by default. I want to just get rid of the SDK and get the up to date version of it.
View 4 Replies View RelatedI have developed an application in C++ that creates some text files in a directory chosen by the user.
How can I ask the user set a Default Directory Path (and some other default parameters) so that she doesn't have to enter the same data in the GUI everytime the application is run.
The application has been developed using Qt Creator.
refer to the code below, the attribute class is created with the value type and default value, but why it doesn't work for std::string?
#include <string>
#include <iostream>
using namespace std;
[Code].....
For example, I have an empty vector of integer. If I keep calling push_back on vector, is it going to be out of memory?
View 8 Replies View RelatedI've been pondering which of these 2 approaches would make for the best interface for a library: Defining custom exceptions with specific names for different error scenarios but with standard behaviour, or simply using the predefined exceptions from the STL.
This is my current approach:
Code:
namespace rpp
{
class ConnectionError : public std::exception
{
public:
ConnectionError(const std::string &p_err);
[Code] .....
This seems to make for more descriptive code but it adds no functionality and the implementations are completely identical, which seems "off" to me, somehow.
I have a question about the default constructor.
To my best understanding, the compiler will provide me with a deafult constructor only if there are no any user defined constructors, at all. Now consider the following code:
Code: class MyClass
{
private:
int m_data;
public:
MyClass(int init):m_data(init){cout<<"Ctr called"<<endl;}
[Code] ....
How is it that suddenly, there is a default constructor?
Same solution that I was having compiler errors on yesterday. We're working with inheritance and the program is supposed to be to create and display information for default Employee objects, Hourly Employee objects and Salaried Employee objects. Everything compiles as is, but I'm running into two issues that I can't figure out.
1) In both the hourly and salaried objects, the wage, hours, and management level attributes all displaying their default values. I'm almost positive that this has something to do with the str to int and str to double conversions that I'm using (currently have atoi and atof in the file, but I've also tried stringstream, but still had to same problem). Any thoughts as to what I'm missing?
2) the assignment calls for the Benefit benefit member in Employee.h to be protected. However this makes the member unaccessible when I try to use it in the EmployeeMain.cpp in order to set the input for the Benefit class members. I had to make the Benefit benefit member public again to get it to compile. How would I set the input for the Benefit class members while the Benefit benefit member is protected?
Solution files follow:
EmployeeMain.cpp
Code:
#include "Hourly.h"
#include "Salaried.h"
void DisplayApplicationInformation();
void DisplayDivider(string);
string GetInput(string);
[Code]....
For example if using FindFirstFile(...) it assumes your passing LCPWSTR and not LPCSTR.
I know I can use FindFirstFileA or FindFirstFileW so what is point of default if always UNICODE.
Which brings to my second question. If I say
FindFirstFile("C:", &fdat);
I get error cannot convert parameter 1 from 'const char [7]' to 'LPCWSTR'
I could say WCHAR fName = "C:"; and pass this variable instead. However is there a way to cast "C:" on-the-fly to LPCWSTR, I tried,
FindFirstFile((LCPWSTR)"C:", &fdat);
But it outputs a stream of LONGs to the console instead of filenames.
I faced a compilation error in the following code :
Code:
#include <iostream>
using namespace std;
void addition(int a, int b = 2, int c);
int main()
[Code]......
My question is that when i have called addition() with the 3rd argument, then what is the necessity of having the default argument for the 3rd parameter ?
I would like to write a program that gives you a few default values. Now you can keep these values by pressing the enter key or you can change them by just typing in new ones and confirm the new values by pressing the enter key again.
Thats as far as i got on my own but it doesn't really work. what i can do to fix this.
Code:
#include<stdio.h>
#include <conio.h>
int getInt(int min, int max);
int main () {
int a[3] = {3,4};
int b;
int code;
[Code]...
I have a dictionary which maps a Guid to Orders, it contains like 350000 orders
Code:
Dictionary<Guid, Order> htPreOrders = new Dictionary<Guid, PreOrder>(350000);
Im trying to optimize it by replacing the IEqualityComparer by a custom one.
Code:
class Comp : IEqualityComparer<Guid> {
public bool Equals(Guid x, Guid y) {
return x == y;
}
public int GetHashCode(Guid obj) {
return obj.GetHashCode();
}
Dictionary<Guid, Order> htPreOrders = new Dictionary<Guid, PreOrder>(350000, new Comp()); would this be faster, or is that the same as the default equality compare of Guid?
im trying to write a file to a default document folder..something like...
FILE* file;
file = fopen("%docdir% est.txt", "w");
fputs("Hello", file);
fclose(file);
"%docdir% est.txt" this isnt working for me, i have to write it as
"C:userspublicdocument est.txt"
any method to write directly to default document folder so it will work in most Windows ? for example in windows 7 this is the default folder "C:users publicdocument est.txt" in windows XP its different
i have to detect the windows version first, to write the correct path
trying to practice the object-oriented part of it by converting my java programs into c++. I believe I understand the concepts of a header file and declaring the functions in the .cpp files. I keep getting this "Undefined reference to NamedStorm::NamedStorm()" error.
NamedStorm.h
#ifndef NAMEDSTORM_H
#define NAMEDSTORM_H
#include <string>
#include <iostream>
// NEVER use using namespce in header, use std instead.
using std::string;
[code]....